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?
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.
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.
Some languages such as C/C++ define many constructs as undefined behavior, while other languages, for example Java, have less undefined behavior [7].
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With