且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在表达式中评估后缀和前缀增量运算符?

更新时间:2023-02-20 22:49:32

C标准未定义执行各种n ++/++ n的顺序,该顺序可能会随时间而改变,或者取决于目标机器和/或优化选项.但是,我认为,编译器仍应创建代码,以原子方式执行每个n ++或++ n.因此,如果Visual Studio显然以n ++结尾(从结果中的"5"可以看出),则它应根据其执行n ++的结果来创建7 7 5或6 8 5.在第二个术语的前面或中间的++ n.

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.

但是G ++也会生成7 85.当我看一下汇编代码时,原因似乎是,G ++从右到左严格按照所有顺序执行所有增量,而且别名中也将别名"++ n"与"n" "之后.从以下代码可以更清楚地看到这一点:

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++;

结果为6 7 4 7 2.因此,显然,在n++的情况下,编译器在增量之前创建n的快照",而在++n的情况下,编译器仅进行增量,后来仅使用n的当前值,当它被写入cout.

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.