后缀增量是否不对返回值执行增量? [英] Does postfix increment perform increment not on returned value?

查看:140
本文介绍了后缀增量是否不对返回值执行增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同样,一个愚蠢的问题。

Again, a silly question.

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
 int i = 0;
 i = i++;
 cout<<i;

 return 0;
}

我得到 1 打印作为这个程序的结果,虽然我预计0:首先一个临时对象创建eing等于0,然后i增量,然后临时对象返回并分配给i。根据:

I get 1 printed as a result of this program though I expected 0: first a temp object created eing equal 0, then i is incremented, then temp object is returned and assigned to i. Just according to:


5.2.6递增和递减[expr.post.incr]
1获得的值
通过应用后缀++是操作数在应用
之前操作数所具有的值
。 [注意:获得的值
是原始
值的副本]

5.2.6 Increment and decrement [expr.post.incr] 1 The value obtained by applying a postfix ++ is the value that the operand had before applying the operator. [Note: the value obtained is a copy of the original value ]

VC 2008和GCC。他们给了两个相同的结果,虽然至少gcc在增量字符串中发出警告。我错了什么?

I checked it under MS VC 2008 and GCC. They give both the same result, though at least gcc issues a warning in incrementation string. Where am I wrong?

推荐答案

i = i++;

未定义。如果单个表达式为变量赋予两个不同的值,C ++规范说任何事情都可能发生 - 它可以取其旧值,两个新值之一,或几乎任何东西。这样做的原因是它允许编译器对简单表达式进行更积极的优化。编译器可以重新安排赋值和 ++ 的执行顺序,例如,如果它认为它更有效率。

is undefined. If a single expression assigns two different values to a variable, the C++ spec says that anything can happen - it could take on its old value, one of the two new values, or pretty much anything at all. The reason for this is that it allows the compiler to make much more aggressive optimizations of simple expressions. The compiler could rearrange the order in which the assignment and ++ are executed, for example, if it thought it were more efficient.

这篇关于后缀增量是否不对返回值执行增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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