C/C++ 中的链式赋值是未定义行为吗? [英] Is chained assignment in C/C++ undefined behavior?

查看:27
本文介绍了C/C++ 中的链式赋值是未定义行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

忽略变量的类型,像 a=b=c 这样的表达式在 C 和 C++ 中都定义了行为吗?

Ignoring the types of variables, is expression like a=b=c has defined behavior in both C and C++?

如果是这样,请谁能给我官方证据,比如引用标准?

If so, can any one give me official evidence, like quotes from the standard, please?

附言我搜索了链式分配,但我得到的一切都是关联性,但我在 C99 标准中没有找到任何关于它的文本.也许我做错了?希望任何人都可以帮助我.

P.S. I searched the chained assignment but everything I got is associativity, but I didn't find any text about that in the C99 standard. Maybe I did it wrong? hoping anyone can help me.

推荐答案

来自 C++ 标准

5.17 赋值和复合赋值运算符 [expr.ass] 1 赋值运算符 (=) 和复合赋值运算符都是从右到左分组.所有都需要一个可修改的左值作为他们的左边操作数并返回一个引用左操作数的左值.结果如果左操作数是位域,则在所有情况下都是位域.在所有在这种情况下,赋值是在值计算之后排序的右操作数和左操作数,在计算值之前赋值表达式.

5.17 Assignment and compound assignment operators [expr.ass] 1 The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

还有一个例子

int a, b;
a = b = { 1 }; // meaning a=b=1;

来自 C 标准

6.5.16 赋值运算符语义3 赋值运算符在左操作数指定的对象中存储一个值.一个任务表达式具有赋值后左操作数的值,111)但不是左值.赋值表达式的类型是类型左操作数在左值转换后会有.副作用更新左操作数的存储值的顺序在左操作数和右操作数的值计算.评价的操作数是无序的.

6.5.16 Assignment operators Semantics 3 An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,111) but is not an lvalue. The type of an assignment expression is the type the left operand would have after lvalue conversion. The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

如您所见,有所不同.在 C++ 中,赋值运算符返回一个引用左操作数的左值,而在 C 中,它返回赋值后左操作数的值,111)但不是左值.

As you see there is a difference. In C++ the assignment operator returns an lvalue referring to the left operand while in C it returns the value of the left operand after the assignment,111) but is not an lvalue.

这意味着在 C++ 中以下代码是有效的

It means that in C++ the following code is valid

int a, b = 20;

( a = 10 ) = b;

而在 C 中,编译器将发出错误.

while in C the compiler shall issue an error.

这篇关于C/C++ 中的链式赋值是未定义行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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