Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
我无法理解该程序的输出(使用 gcc
)。
main()
{
int a=10;
printf("%d %d %d\n",++a, a++,a);
}
输出:
12 10 12
另外,请解释 printf()
的参数求值顺序.
最佳答案
编译器将按照当时感觉的任何顺序评估 printf
的参数。这可能是一个优化的事情,但不能保证:它们的评估顺序不是由标准指定的,也不是实现定义的。没有办法知道。
但是标准所指定的是,在一次操作中两次修改同一变量是未定义的行为; ISO C++03, 5[expr]/4:
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.
printf("%d %d %d\n",++a, a++,a);
可以做很多事情;按照您期望的方式工作,或者以您永远无法理解的方式工作。
你不应该编写这样的代码。
关于c - printf ("%d %d %d\n",++a,a++,a) 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27740332/