I am trying to compare two integer variables to a same constant. Apparently in this case, both variables have the same default values. I tried to simplify the comparison statement like this:
if (po->app_tag == po->inst_id == 0)
return 1;
It didn't work.
I had to code it like:
if ((po->app_tag == 0) && (po->inst_id == 0))
return 1;
To make it work. Can anyone explain to me the difference between the two? Somehow I feel that C compiler should have a provision for this kind of syntax when it comes to comparison of two integer variables. I can be wrong asking for it.. :), but want to understand a reason.. Why am I wrong here.
Due to associativity of the ==
operator (it associates from left to right),
po->app_tag == po->inst_id == 0
is interpreted as:
(po->app_tag == po->inst_id) == 0
That's how the language is defined.
Using
(po->app_tag == 0) && (po->inst_id == 0)
fixes that problem by evaluating po->app_tag == 0
and po->inst_id == 0
independently and performing a boolean AND between those two.
See http://en.cppreference.com/w/c/language/operator_precedence for more info on operator precedence and associativity.