How is the postfix and prefix increment operator evaluated in an expression? [duplicate]

ぐ巨炮叔叔 提交于 2019-12-02 13:36:58

The sequence, in which the various n++ / ++n are executed, is undefined by the C standard and might change over time or depending on target machine and/or optimization options. However, I think, a compiler SHOULD still create code, that executes each of the n++ or ++n in an atomic fashion. So, if Visual Studio apparently starts with the n++ at the end (as can be seen from the "5" in the result), then it should create either 7 7 5 or 6 8 5 as result, depending on whether it executes the n++ in front or the ++n in the middle as second term.

But G++ also produces 7 8 5. When I look at the assembly code, the reason seems to be, that G++ does all the increments in strict order from right to left, but also aliases "++n" with "n" later. This can be seen more clearly from this code:

int n = 2;
cout << n++ << " " << ++n << " " << n++ << " " << ++n << " " << n++;

The result is 6 7 4 7 2. So apparently, in case of n++, the compiler creates a "snapshot" of n before the increment, while in case of ++n, the compiler just does the increment and later just uses the current value of n, when it is written to cout.

Of course, the result of having two increments to the same value is undefined, so the compiler's choice is completely legal.

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