如何在 C 程序中评估增量运算符?

How is the increment operator evaluated in C programs?

我有两种表达方式:

int a=5; 
int c=++a;// c=6, a=6
int b=a++;// b=6, a=7

在第二条指令中,首先计算增量,在第三条指令中,在赋值之后计算增量。

我知道自增运算符有更高的优先级。谁能给我解释一下为什么它在第三个表达式赋值后求值?

结果与运算顺序无关,与前缀++和后缀++的定义有关。

表达式 ++a 的计算结果为 a 的增量值。相反,表达式 a++ 的计算结果为 acurrent 值,并且 a 作为副作用递增。

C standard 的第 6.5.2.4p2 节对后缀 ++ 说了以下内容:

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

第 6.5.3.1p2 节对前缀 ++ 说了以下内容:

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1)

++aa++ 只是不同的运算符,尽管符号 ++ 相同。一种是前缀递增,一种是后缀递增。与分配相比,这与优先级无关。 (就像 a - b-a 是不同的运算符,尽管符号 - 相同。)

编辑: 有人指出这是关于 C 而不是 C++...哎呀。所以,如果你只知道C,下面的解释可能会让人感到困惑;你只需要知道 int& 是对 int 的引用,所以它就像有一个指针但不需要取消引用它,所以在这些函数内部修改 a 实际上会修改您传递给函数的变量。

你可以把它们想象成函数:

int prefixIncrement(int& a) {
  return ++a;
}

...等同于:

int prefixIncrement(int& a) {
  a += 1;
  return a;
}

并且:

int postfixIncrement(int& a) {
  return a++;
}

...等同于:

int postfixIncrement(int& a) {
  int old = a;
  a += 1;
  return old;
}

对于吹毛求疵的人:是的,实际上我们需要在 postfixIncrement 的 return 值上移动语义。