c - printf ("%d %d %d\n",++a,a++,a) 输出

标签 c printf

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/

相关文章:

c - for循环中的变量在同一循环中具有不同的值(C语言)

c - printf 语句未在 netbean 中的 scanf 语句之前执行

c - 进程是从其父进程继承其环境变量还是从 Windows 获取它们?

c - 无法从函数返回 char 指针

c - 实时时钟、增量并显示在 C 语言的 LED 上

c - 如何允许用户在我的 CLI 中定义变量?

c++ - 有没有更优雅的方式在 C++ 中结合 sprintf 和 std::string?

c - printf 在类型与类型说明符不匹配的情况下如何工作?

c - 在 C 中使用 wcslen 时出现段错误

c++ - 如何在数组中找到非耦合整数?