如何在表达式中评估后缀和前缀增量运算符? [英] How is the postfix and prefix increment operator evaluated in an expression?

查看:90
本文介绍了如何在表达式中评估后缀和前缀增量运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
 int n = 5;

 cout<< n++ <<" "<< ++n << " "<< n++;

 _getch();
 return 0;
}

当我在Visual Studio上运行此程序时,输出为7 8 5.

When I run this program on Visual Studio the output is 7 8 5.

我认为它取决于编译器. (如果我错了,请纠正我) 但是不是7 7 5还是5 7 7?

I think it is compiler dependent. ( Correct me if I am wrong) But shouldn't it be either 7 7 5 or 5 7 7 ?

推荐答案

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.

这篇关于如何在表达式中评估后缀和前缀增量运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆