Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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.

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!

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top