“错误:作为赋值的左操作数需要左值";在条件运算符中 [英] "error: lvalue required as left operand of assignment" in conditional operator

查看:197
本文介绍了“错误:作为赋值的左操作数需要左值";在条件运算符中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,今天我学到了?"运算符,它是if-else语句的简短类型.但是,当我执行以下代码时:

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

我收到一个错误错误:左值必须作为赋值的左操作数".我不明白为什么会这样.在我看来,程序首先将34赋给x,然后将x的值34赋给b. 另一方面,我可以将语句用作

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

没有任何错误.我看了看书,但无济于事.为什么我不能使用第一条陈述?我的电脑想做什么? 谢谢...

解决方案

+1有趣的问题-它突出显示了C ++和C之间的两个区别.

(1)C和C ++中三元表达式的求值规则不同

C ++解析如下

logical-OR-expression ? expression : assignment-expression

因此它通过匹配assignment-expressionx=34

来解析您的语句

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

但是C会这样解析

logical-OR-expression ? expression : conditional-expression 

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆