Dervin Thunk
Dervin Thunk

Reputation: 20119

Ternary operator and lvalues in C

Suppose I have a linked list L which may be NULL or not. When I try

   !L ? s+=2 : t+=2;

The compiler complains that lvalue is required as left operand of assignment. What am I missing? Operator precedence, maybe?

Upvotes: 1

Views: 447

Answers (2)

Oktalist
Oktalist

Reputation: 14714

The relevant grammar production is:

conditional-expression:

logical-OR-expression

logical-OR-expression ? expression : conditional-expression

t+=2 is not a conditional-expression, so the compiler must interpret !L ? s+=2 : t+=2 as equivalent to (!L ? s+=2 : t)+=2. In C, a conditional expression never yields an lvalue, so cannot appear to the left of +=.

(t+=2) is a conditional-expression, so !L ? s+=2 : (t+=2) is correct.


For reference, in C++ the relevant grammar production is:

conditional-expression:

logical-or-expression

logical-or-expression ? expression : assignment-expression

t+=2 is an assignment-expression, so !L ? s+=2 : t+=2 is valid C++, and does what you think.

Interestingly, in C++, the conditional operator can yield an lvalue, if the undecayed common type of its second and third operands is an lvalue. But if my reading of the standard is correct, then this fact has no bearing on this case.

Upvotes: 4

gsamaras
gsamaras

Reputation: 73366

In C you should use parentheses in the second term, because of operator precedence as you thought. !L ? s+=2 : (t+=2);

In C++, you don't need the parentheses.

Upvotes: 2

Related Questions