Reputation: 1031
I was looking into a code snippet and saw below statement. How will below statement evaluated?
x= 5|(high == 1 ? y : high == 0 ? z:0);
Upvotes: 0
Views: 91
Reputation: 223739
From The C99 standard, section 6.5.15.4:
The first operand is evaluated; there is a sequence point after its evaluation. The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (which ever is evaluated), converted to the type described below. If an attempt is made to modify the result of a conditional operator or to access it after the next sequence point, the behavior is undefined.
Because operands are evaluated left to right, the second instance of the ternary operator (all three parts) becomes the expression in the third part of the first ternary operator.
So this:
high == 1 ? y : high == 0 ? z:0
is equivalent to this:
(high == 1) ? y : ((high == 0) ? z:0)
Upvotes: 0
Reputation: 106012
The expression
x= 5|(high == 1 ? y : high == 0 ? z:0);
is evaluated as
x= 5|( high == 1 ? y : (high == 0 ? z:0) );
It has similar effect as that of
if(high == 1)
x = 5|y;
else if(high == 0)
x = 5|z;
else
x = 5|0;
Upvotes: 3