简单但令人困惑的C代码

问题描述:

#include<stdio.h>
main()
{
      int i=5;
      printf("%d",++i + ++i + ++i);
}



谁能告诉我这是如何打印的22 .. ??



Can anyone tell me how this prints 22..??

它首先计算++ i + ++ i,意外结果为14,因为该运算是i + i,但在执行此操作之前先将其递增.结果保存到某个位置,例如注册表,然后我又增加了一次并添加到保存的结果中.

由于i + i + i,即使这样也可以给24.首先对++ i进行评估,然后对它进行一次又一次的评估.完成之后,操作结果= i + i + i
It first evaluates ++i + ++i, the unexpected result is 14, because the operation is i + i, but before doing this it is incremented. The result is saved to some place, for instance the registry, and after that i is incremented one more time and added to the saved result.

Even this may give 24, because of i + i + i. First is evaluated ++i, after that it is evaluated again and again. And after that is done operation result = i + i + i


全部归结为编译器生成代码的顺序.通常,这种构造永远都不能在实时代码中使用,因为这样容易产生错误的结果.用调试器逐步检查生成的汇编代码,以查看发生了什么.
It''s all down to the order in which the compiler generates the code. In general this sort of construct should never be used in live code as it is prone to giving the wrong result. Step through the generated assembler code with your debugger to see what is happening.


带有-Wall开关的GCC编译器会给出以下警告:
The GCC compiler with the -Wall switch, gives the following warnings:
j.c:5: warning: operation on ‘i’ may be undefined
j.c:5: warning: operation on ‘i’ may be undefined



在堆栈溢出中很好地解释了为什么可能不确定该操作的原因: printf和++运算符[关闭] [ ^ ].



Why the operation might be undefined is well explained at Stack Overflow: printf and ++ operator [closed][^].