x = y = z = 1;
z = ++x||++y&&++z;
operator precedence is as follows --
(pre-increment) > && > ||
so answer should be--
1. 2||2 && 2
2. 2||1
3. 1
print x,y,z should be 2,2,1
but, answer is 2,1,1.
Precedence is not the same as order of evaluation. Precedence simply determines what operands and operators belong together. The exact order of evaluation is unspecified except with the logical operators, which are evaluated in strict left-to-right order to enable short-circuiting.
So because &&
has higher precedence, the variables are first grouped as follows:
(++x) || (++y && ++z)
Then, following left-to-right order, ++x
is evaluated. Given that ++x
is true, it is known that the entire expression is true. So expression evaluation is short-circuited. (++y && ++z)
never gets evaluated. Hence y and z never get incremented.
Expressions with logical operators &&
and ||
evaluate left to right:
C99, Section 6.5.14-4 Unlike the bitwise
|
operator, the||
operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to0
, the second operand is not evaluated.
Since x++
is not zero, the expression short-circuits evaluation of everything to the right of ||
, including their side effects. That's why only x++
is evaluated, so x
becomes 2
. The remaining variables stay at 1
, as they should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With