简体   繁体   中英

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?

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 !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) !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 !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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM