Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous operator precedence, please explain why operator predence is not followed here? [duplicate]

Tags:

c

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.

like image 587
phoenix Avatar asked Nov 28 '22 15:11

phoenix


2 Answers

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.

like image 173
verbose Avatar answered Dec 21 '22 11:12

verbose


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 to 0, 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.

like image 30
Sergey Kalinichenko Avatar answered Dec 21 '22 11:12

Sergey Kalinichenko