Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple compound assignments in a single statement: is it Undefined Behavior or not?

I can't find a definitive answer for this: does the following code have undefined behavior?

int x = 2;
x+=x+=x+=2.5;
like image 736
makefun Avatar asked Jun 18 '13 10:06

makefun


1 Answers

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.

like image 140
interjay Avatar answered Oct 22 '22 00:10

interjay