Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence of Logical Operators in C [duplicate]

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").

like image 441
Daniel Scocco Avatar asked Sep 22 '11 21:09

Daniel Scocco


1 Answers

Just try to imagine it with parentheses:

++a || ++b && ++c;

equals

(++a) || (++b && ++c);

which is evaluated from left to right.

if && and || would have the same precedence, it would look like

(++a || ++b) && (++c);
like image 177
helios35 Avatar answered Oct 05 '22 11:10

helios35