首页 新闻 赞助 找找看

关于i++与++i的疑问

0
[已解决问题] 解决于 2011-12-10 19:45

请看下面的代码:

#include <stdio.h>
main()
{
int i=9;
printf(
"%d %d %d\n",++i,i,--i);
printf(
"%d %d %d\n",i++,i,i--);
}
运行结果是

9 8 8

8 8 9

谁来解释下原因啊?

hailong的主页 hailong | 初学一级 | 园豆:70
提问于:2010-11-07 21:57
< >
分享
最佳答案
0

不知道LZ的编译器是什么?对于这个问题,不同编译器有不同结果。

 

总的思路是这样的:

首先,要明确:

 C 程序中,堆栈 用于 传递函数参数,
 而且对C编译器 默认的调用方式,如:_cdecl和_stdcall,
 需要调用方把参数反序(从右到左)压入堆栈,并由被调用方(_cdecl方式)或调用方恢复堆栈(_stdcall)。

所以,对于

printf("%d %d %d\n",i++,i,i--); 这句:

先计算 i--,
再获取 i,
最后 计算 i++;

而打印时的顺序(根据“栈”的FILO)为 i++, i, i--;

就是这样的。。你可以在不同编译上试试。
惠歌子 | 菜鸟二级 |园豆:210 | 2010-11-10 22:36
其他回答(4)
0

In C++ ISO/IEC 14882:2003 --- 5 Expressions

4. Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

嗷嗷 | 园豆:757 (小虾三级) | 2010-11-07 22:00
嘛意思啊
支持(0) 反对(0) hailong | 园豆:70 (初学一级) | 2010-11-07 22:09
0

就是在printf("%d %d %d\n",++i,i,--i);中++i,i,--i的执行顺序是不确定的。

不一定++i在最前面就先执行,有可能--i先执行的。

wang_yb | 园豆:4891 (老鸟四级) | 2010-11-08 13:31
0

这可能与平台有关吧,编译时从后面到前面进行翻译。

fishall | 园豆:300 (菜鸟二级) | 2010-11-16 17:17
0

因为你的编译器从右到左解释了。所以。。。。

在有些编译器也许不是这个顺序,所以,最好写平台无关的代码。

fangyukuan | 园豆:215 (菜鸟二级) | 2010-12-22 18:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册