C/C ++中的链接分配是未定义的行为吗? [英] Is chained assignment in C/C++ undefined behavior?

查看:79
本文介绍了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?

P.S.我搜索了链接的分配,但是我得到的都是关联性,但是在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天全站免登陆