When does postincrement i++ get executed? [duplicate]

十年热恋 提交于 2019-11-28 02:09:34

Instead of jumping on the details of the example that is UB, I will discuss the following example that is perfectly fine:

int a = 0, b = 0;
int c = a++ + b++;

Now, the precedence of operators means that the last line is equivalent to:

int c = (a++) + (b++);

And not:

int c = (a++ + b)++; // compile time error, post increment an rvalue

On the other hand, the semantics of the post increment are equivalent to two separate instructions (from here on is just a mental picture):

a++; // similar to: (__tmp = a, ++a, __tmp) 
     // -- ignoring the added sequence points of , here

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 reorder the 5 instructions as long as the following constraints are met (where x>y means x must be executed before y, or x precedes y):

1 > 3        // cannot increment a before getting the old value
2 > 4        // cannot increment b before getting the old value
1 > 5, 2 > 5 // the sum cannot happen before both temporaries are created

There are no other constraints in the order of execution of the different instructions, so the following are all valid sequences:

1, 2, 3, 4, 5
1, 2, 5, 3, 4
1, 3, 2, 4, 5
...
sharptooth

This

int y = x++ + x++ ;

is undefined behavior. Anything can happen, including some unreasonable results, program crashing or whatever else. Just don't do that.

In C++ there are things called "sequence points". If you alter a value more than once without an intervening sequence point, the behaviour is undefined.

Consider the following:

int x = 0;
int y = x++ + x++;

The value of y could be 0, 1 or some other completely random value.

Bottom line is, don't do it. Nothing good can come of it. :-)

In your case, is seems like the following happens

When you use x++, x increments after the operation is complete.

int y = x++ + x++ ;
// First add 0+0
// Increment x
// Increment 

While

int y = ++x + ++x ;
// Add (increment x) and (increment x) = 1+1 = 2

However, different compilers will handle it differently and your application might crash if you increment twice in the same statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!