Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in ternary operator

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?

like image 652
samuelbrody1249 Avatar asked Mar 21 '26 17:03

samuelbrody1249


2 Answers

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;
like image 151
dbush Avatar answered Mar 23 '26 06:03

dbush


The :? has higher operator precedence than assignment operator. So the latter is equivalent to:

(a > b ? ' ' : b)=4;

Which is obviously illegal.

like image 45
Eugene Sh. Avatar answered Mar 23 '26 08:03

Eugene Sh.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!