“error: lvalue required as left operand of assignment” in conditional operator

无人久伴 提交于 2019-12-01 19:54:46

问题


I'm new to C and today I learnt "?" operator which is the short type of if-else statement. However, when I execute this code:

int b;
int x;
b=3<2?x=12:x=34;

I get an error "error: lvalue required as left operand of assignment". I don't understand why it happens. Process in my mind is that the program first assigns 34 to x, then it assigns value of x,which is 34, to b. On the other hand, I can use the statement as

int b;
int x;
b=3<2?x=12:(x=34);

without any errors. I looked to my book but nothing helped. Why can't I use the first statement? What is my computer trying to do? Thanks...


回答1:


+1 for interesting question - it highlights two differences between C++ and C.

(1) The evaluation rules for ternary expressions are different in C and C++

C++ parses as follows

logical-OR-expression ? expression : assignment-expression

It is therefore parsing your statement by matching assignment-expression to x=34

b = 3<2 ? x = 12 : (x = 34);

But C parses like this

logical-OR-expression ? expression : conditional-expression 

x = 34 is not a conditional-expression so your statement gets parsed like

b = (3<2 ? x = 12 : x) = 34;

(2) The conditional operator in C++ can return an lvalue, whereas C cannot. Hence, the following is legal in C++ but not in C:

b = (3<2 ? x = 12 : x) = 34;

Verified on ideone.com for C and C++ compilers. See also these links Errors using ternary operator in c for diff between C and C++ ternary operator Conditional operator differences between C and C++ for diff in lvalue rules



来源:https://stackoverflow.com/questions/40388689/error-lvalue-required-as-left-operand-of-assignment-in-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!