“错误:左值需要作为赋值的左操作数";在条件运算符中 [英] "error: lvalue required as left operand of assignment" in conditional operator
问题描述
我是 C 新手,今天我学会了?"运算符,它是 if-else 语句的短类型.但是,当我执行此代码时:
int b;整数 x;b=3<2?x=12:x=34;
我收到一个错误错误:左值需要作为赋值的左操作数".我不明白为什么会这样.我心目中的过程是程序先给x赋值34,然后再给b赋值x的值,即34.另一方面,我可以将语句用作
int b;整数 x;b=3<2?x=12:(x=34);
没有任何错误.我看了看我的书,但没有任何帮助.为什么我不能使用第一个语句?我的电脑想做什么?谢谢...
+1 有趣的问题 - 它突出了 C++ 和 C 之间的两个差异.
(1) C 和 C++ 中三元表达式的求值规则不同
C++解析如下
逻辑或表达式?表达式:赋值表达式
因此,它通过将 assignment-expression
与 x=34
b = 3<2 ?x = 12 : (x = 34);
但是 C 是这样解析的
逻辑或表达式?表达式:条件表达式
x = 34
不是 conditional-expression
所以你的语句被解析为
b = (3<2 ? x = 12 : x) = 34;
(2) C++ 中的条件运算符可以返回一个 lvalue
,而 C 不能.因此,以下内容在 C++ 中合法,但在 C 中不合法:
b = (3<2 ? x = 12 : x) = 34;
在 ideone.com 上验证了 C 和 C++ 编译器.另请参阅这些链接在 c 中使用三元运算符的错误 用于 C 和 C++ 三元运算符之间的差异C 和 C++ 之间的条件运算符差异用于左值规则中的差异>
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 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
这篇关于“错误:左值需要作为赋值的左操作数";在条件运算符中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!