Reputation: 669
If the precedence of && is greater than that of ||, shouldn't this code evaluate --b && ++c first, and thus the output should be 1 2 4 11. But here it seems to be short circuited to give 1 2 5 10. Please help!
int x;
int a=1,b=5,c=10;
x=a++||--b&&++c;
printf("%d %d %d %d\n",x,a,b,c);
return 0;
Upvotes: 5
Views: 1893
Reputation: 75130
The precedence of &&
is higher, which means it binds tighter to the things on the left and right of it than ||
. So that expression is equivalent to
a++ || (--b && ++c)
||
only evaluates the thing on the right if the expression on the left evaluates to non-0. Since a is 1
, only a++
will be evaluated, and b
will not be decremented and c
will not be incremented.
Upvotes: 2
Reputation: 447
There are two concepts at work here
In C, || operator is left associative. As a result, a++ will be evaluated first.
Since the left side is TRUE, compiler optimization short-circuiting will make sure that the right side of the || is not evaluated because it will not change the result of the expression.
Upvotes: 1
Reputation: 56059
Yes, &&
has higher precedence, but that only determines the grouping of the operands, not the order of evaluation. The base operation here is ||
, which guarantees its right side is not evaluated if the left is true, regardless of what operations are on the right-hand side.
Upvotes: 2
Reputation: 258608
shouldn't this code evaluate --b && ++c first
No Operator precedence doesn't affect evaluation order. It just means that
a++||--b&&++c
is equilvalent to
a++||(--b&&++c)
so it's still a++
that is evaluated first, and thus short-circuits the statement.
Upvotes: 13