Is chained assignment in C/C++ undefined behavior?

橙三吉。 提交于 2019-12-09 17:08:58

问题


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. 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.


回答1:


From the C++ Standard

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.

And an example from there

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

From the C Standard

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.

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.

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

int a, b = 20;

( a = 10 ) = b;

while in C the compiler shall issue an error.




回答2:


It is all about associativity. You can rewrite a=b=c as a=(b=c). And the result of an assignment (b=c) is the value of the last assigned variable (b).




回答3:


It C, and C++, assignment is right associative and also an expression, so

a=b=c;

Is treated as:

a=(b=c);

Where the expression b=c evaluates to whatever is in b after the assignment. Note that I say "whatever` as it's possible (but not advisable) in C++ to provide an assigment function that does something other that assignment!




回答4:


According to §6.5.16 (3) of C99:

An assignment expression has the value of the left operand after the assignment, [...]

Together with right-associativity of evaluation, and assuming non-volatile a, b, and c, it means that a = b = c is equivalent to a = (b = c), and again equivalent to b = c; a = b.



来源:https://stackoverflow.com/questions/22609067/is-chained-assignment-in-c-c-undefined-behavior

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