C(++ a和a ++)中前缀和后缀增量之间的差异

时间:2014-12-15 09:45:57

标签: c increment postfix-operator prefix-operator

据我所知,a ++是后缀增量,它将1加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;
}

4 个答案:

答案 0 :(得分:0)

a也会增加1.

如果您有类似

的内容
p = a++;

这里

p = 0

如果你有

p = ++a;

这里

p =1

因此,您可以将变量的值分配给其他变量,如上所示,并测试post和pre increment的变化。

答案 1 :(得分:0)

如果是前缀增量,则会计算++..运算符并首先执行增量,然后该增量值将成为操作数。

如果是后增量,则会对..++运算符进行求值,并在包含该操作数的其他求值完成后调度增量。这意味着,操作数的现有值在另一个评估中使用,然后值增加。

要更好地理解它,请使用另外两个变量cd,并检查以下值。

#include <stdio.h>
int main() {
  int a = 0;
  int b = 0;
  int c = 0;
  int d = 0;   

  printf("%d\n", a); // prints 0
  printf("%d\n", b); // prints 0

  c = a++; // a++ is known as postfix. Add 1 to a, returns the old value.
  d = ++b; // ++b is known as prefix. Add 1 to b, returns the new value.

  printf("%d\n", a);   // is 1
  printf("%d\n", b);    // is 1
  printf("%d\n", c);    // is 0; --> post-increment
  printf("%d\n", d);    // is 1  --> pre-increment

  return 0;
}

答案 2 :(得分:0)

请记住,C和C ++是一种表达性语言。

这意味着大多数表达式返回一个值。如果你没有对这个价值做任何事情,它就会失去时间。

表达式

(a++)

将返回a以前的值。如前所述,如果当时和那里没有使用它的返回值,那么它与

相同
(++a)

返回新值。

printf("%d\n", a++); // a's former value
printf("%d\n", ++b); // b's new value

以上陈述将按预期运作,因为您正在使用那里的表达。

以下也可以。

int c = a++;
int d = ++b;

printf("%d\n", c); // a's former value
printf("%d\n", d); // b's new value

答案 3 :(得分:0)

a会递增,但会返回旧值。但由于它在一条线上,因此忽略了结果。试试这个来说明差异:

#include <stdio.h>
int main() {
  int a = 0;
  int b = 0;

  printf("%d\n", a++);
  printf("%d\n", ++b);

  return 0;
}