【发布时间】:2013-08-27 19:28:47
【问题描述】:
我今天看到一个关于后增量和前增量的有趣声明。请考虑以下程序-
#include <stdio.h>
int main(){
int x, z;
x = 5;
z = x++ - 5; // increase the value of x after the statement completed.
printf("%d\n", z); // So the value here is 0. Simple.
x = 5;
z = 5 - ++x; // increase the value of x before the statement completed.
printf("%d\n", z); // So the value is -1.
// But, for these lines below..
x = 5;
z = x++ - ++x; // **The interesting statement
printf("%d\n", z); // It prints 0
return 0;
}
那个有趣的陈述实际上发生了什么?后增量应该在语句完成后增加 x 的值。那么对于该语句,first x 的值仍为 5。而在预增量的情况下,second x 的值应该是 6 或 7(不确定)。
为什么它给出的值是0 到 z?是 5 - 5 还是 6 - 6?请解释一下。
【问题讨论】:
-
您将进入未定义的行为,这实际上取决于编译器如何处理它。
-
还有this one。
标签: c++ c post-increment pre-increment