For a ternary operator, why does the following compile:
a > b ? a=4 : ' ';
But this one does not:
a > b ? ' ' : b=4;
lvalue required as left operand of assignment
That is, what makes the true case different than the false case for assignment?
It has to do with the formal definition of the conditional operator. From section 6.5.15 of the C standard:
conditional-expression: logical-OR-expression logical-OR-expression ? expression : conditional-expression
The second clause of a conditional can be any expression, while the third clause can only be a conditional expression (of which as assignment is not). Put another way, the conditional operator ?: has higher precedence than the assignment operator =.
So this:
a > b ? a=4 : ' '
Is the same as this:
(a > b) ? (a=4) : (' ')
But this:
a > b ? ' ' : b=4;
Is the same same as this:
((a > b) ? (' ') : b)=4;
And the result of the conditional operator cannot be assigned to (i.e. it is not an lvalue) so you get an error.
If you add parenthesis you can get something that compiles:
a > b ? ' ' : (b=4);
Granted, these statements don't look like the best use case for a conditional and should probably be rewritten as:
if (a>b) a=4;
And:
if (a<=b) b=4;
The :? has higher operator precedence than assignment operator. So the latter is equivalent to:
(a > b ? ' ' : b)=4;
Which is obviously illegal.
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