Possible Duplicate:
why “++x || ++y && ++z” calculate “++x” firstly ? however,Operator “&&” is higher than “||”
If you look at C's precedence table, you'll see that && has higher precedence than ||.
But take a look at the following code:
a=b=c=1;
++a || ++b && ++c;
printf("%d %d %d\n",a,b,c);
It prints out "2 1 1", meaning that the "++a" is evaluated first, and once the program sees a TRUE there it stops right there, because what is on the other side of the || is not important.
But since && has higher precedence than ||, shouldn't "++b && ++c" be evaluated first, and then the result plugged back into "++a || result" ? (in this case the program would print "1 2 2").
Precedence and order of evaluation are two completely different things. For logical operator expressions, evaluation is always left-to-right. The expression
++a || ++b && ++c
is interpreted asThe expression is parsed as
++a || (++b && ++c)
; the whole expression is true if either of the subexpressions++a
or++b && ++c
is true.The precedence rules only say that it will be evaluated like this:
Now comes the short circuiting behavior of the logic operators which says that you have to evaluate terms from left to right and stop when the result is known. The part on the right never gets executed.
&& has higher precedence
only in parse tree. But compiler optimizes the code asYour example
++a || ++b && ++c
is the same as++a || (++b && ++c)
.Just try to imagine it with parentheses:
equals
which is evaluated from left to right.
if && and || would have the same precedence, it would look like