【发布时间】:2014-12-15 09:45:57
【问题描述】:
据我了解,a++ 是后缀自增,它将 a 加 1 并返回原始值。 ++a 是前缀递增,它给广告加 1 返回新值。
我想尝试一下,但在这两种情况下,它都会返回新值。我误会了什么?
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
printf("%d\n", a); // prints 0
printf("%d\n", b); // prints 0
a++; // a++ is known as postfix. Add 1 to a, returns the old value.
++b; // ++b is known as prefix. Add 1 to b, returns the new value.
printf("%d\n", a); // prints 1, should print 0?
printf("%d\n", b); // prints 1, should print 1
return 0;
}
【问题讨论】:
-
不,只有当你有类似 printf("%d\n", a++); printf("%d\n", ++b);
-
行为是正确的,你对后增量的理解是错误的。如果您执行
printf("%d\n", a++);,您想要的行为将是可观察的,它会打印然后会增加。在你的情况下,它会增加,然后你打印它。 -
你没有使用返回值,所以你不应该期望看到差异
-
不知道为什么会有大量的反对票。这本身并不是一个坏问题。肯定存在大量糟糕问题的文化,而这并不真正属于这一类。
-
谢谢Qix。如果已经存在类似的问题,我想我应该更彻底地检查一下。
标签: c increment postfix-operator prefix-operator