Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the following chained assignment cause Undefined behavior?

Does the following code invoke undefined behavior in C?

int a = 1, b = 2;
a = b = (a + 1);

I know that the following does invoke UB:

a = b = a++;

The reason is that it violates the following clause from the standard:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

However, the first snippet does not violate this clause. A coworker says that statement a = b = a+1 can mean either

a = a + 1;
b = a + 1;

or

b = a + 1;
a = b;

I think that due to the "right-to-left" associativity of =, it always must mean a = (b = (a+1)), not

a = a + 1;
b = a + 1;

I'm not positive, though. Is it UB?

like image 513
anjruu Avatar asked May 18 '15 13:05

anjruu


People also ask

What causes undefined behavior in C?

So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

What is chained assignment in C++?

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.

Does Java have undefined behavior?

Some languages such as C/C++ define many constructs as undefined behavior, while other languages, for example Java, have less undefined behavior [7].

What is undefined Behaviour in C?

In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres.


1 Answers

IMHO, a = b = a+1 is well-defined.

Here. you're not changing the value of a, just using it, in case of a+1.

To be explicit, according to the "right-to-left" associativity of = operator, you can break down the above as,

b = a + 1;  //a does not change here, only the value is used.
a = b;
like image 195
Sourav Ghosh Avatar answered Nov 14 '22 21:11

Sourav Ghosh