Instead of retelling the details of the UB example, I will talk about the following example, which works great:
int a = 0, b = 0; int c = a++ + b++;
Now, operator precedence means the last line is equivalent:
int c = (a++) + (b++);
And not:
int c = (a++ + b)++;
On the other hand, the semantics of incremental incrementation is equivalent to two separate instructions (hence only the mental picture):
a++;
That is, the original expression will be interpreted by the compiler as:
auto __tmp1 = a; // 1 auto __tmp2 = b; // 2 ++a; // 3 ++b; // 4 int c = __tmp1 + __tmp2; // 5
But the compiler is allowed to change the order of 5 instructions until the following restrictions are satisfied (where x>y means x must be executed before y or x preceded by y ):
1 > 3
There are no other restrictions in the execution order of the various instructions, so the following valid sequences are:
1, 2, 3, 4, 5 1, 2, 5, 3, 4 1, 3, 2, 4, 5 ...
David Rodríguez - dribeas
source share