Reputation: 1095
PROGRAM
#include <stdio.h>
int main(void)
{
int i, j, k;
i = 1; j = 1; k = 1;
printf("%d ", ++i || ++j && ++k);
printf("%d %d %d", i, j, k);
return 0;
}
OUTCOME
1 2 1 1
I was expecting 1 1 2 2. Why? Because the && has precedence over ||. So I followed these steps: 1) j added 1, so j now values 2... 2) k added 1, so k now values 2... 3) 2 && 2, evaluates to 1... 4) No need of further evaluation as the right operand of || is true, so the whole expression must be true because of short circuit behavior of logical expressions...
Why am I wrong?
Upvotes: 8
Views: 862
Reputation: 122383
Precedence affects only the grouping. &&
has a higher precedence than ||
means:
++i || ++j && ++k
is equivalent to:
++i || (++j && ++k)
But that doesn't mean ++j && ++k
is evaluated first. It's still evaluated left to right, and according to the short circuit rule of ||
, ++i
is true, so ++j && ++k
is never evaluated.
Upvotes: 13