c - 如何用优先表证明 C 后缀增量运算符的合理性?

标签 c increment operator-precedence postfix-operator

我正在使用 C 运算符优先级表以更好地理解 C 的运算符优先级。我在理解以下代码的结果时遇到问题:

int a, b;
a = 1;
b = a++;   // does not seem to follow C operator precedence

使用 C 运算符的优先级表,我无法解释为什么使用后缀 ++ 运算符,首先计算赋值,然后计算增量。

后缀自增运算符(++)在C语言中的优先级最高,而赋值运算符(=)的优先级最低。所以在上面的代码中,必须首先执行后缀++,然后赋值=。因此,变量 ab 都应该等于 2,但它们不是。

为什么 C 运算符优先级似乎不适用于此代码?

后缀++的最高优先级什么时候不显示出来?

最佳答案

这与优先级无关。这是后缀 ++ 运算符如何工作的问题。

后缀 ++ 运算符计算其操作数的当前 值,并且 具有递增其操作数的副作用。相比之下,前缀 ++ 运算符的计算结果为其操作数的递增值。

int a, b;
a = 1;
b = a++;   // b is 1, a is 2
b = ++a;   // b is 3, a is 3

后缀 ++ 运算符的这种行为记录在 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). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. Postfix ++ on an object with atomic type is a read-modify-write operation with memory_order_seq_cst memory order semantics.

前缀 ++ 运算符在 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) . See the discussions of additive operators and compound assignment for information on constraints, types, side effects, and conversions and the effects of operations on pointers.

关于c - 如何用优先表证明 C 后缀增量运算符的合理性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561978/

相关文章:

C - 调试二维数组的特定子数组

c - 时间逼近算法?

C# For 循环不递增

c - 为什么这些构造使用增量前和增量后未定义的行为?

c++ - 重载逗号运算符*真的*会影响其操作数的评估顺序吗?

C Random numbers for ASCII,为什么这段代码是错误的?

c - 收到警告 : assignment from incompatible pointer type for using pointer to char array in struct

ruby-on-rails - Rails 中的计数器缓存 : 'increment_counter' works, 'increment' 不是吗?

haskell - Haskell 中状态单子(monad)的增量函数

c++ - 链接 boolean 值给出与预期相反的结果