I can't find a definitive answer for this: does the following code have undefined behavior?
int x = 2;
x+=x+=x+=2.5;
The behavior is undefined. Let's look at the slightly simpler expression:
x += (x+=1)
In C++11, the value computation of the left x is unsequenced relative to the value computation of the expression (x+=1). This means that value computation of x is unsequenced relative to the assignment to x (due to x+=1), and therefore the behavior is undefined.
The reason for this is that the value computation of the two sides of the += operator are unsequenced relative to each other (as the standard doesn't specify otherwise). And 1.9p15 states:
If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
In C++03 the behavior is undefined because x is modified twice without an intervening sequence point.
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