gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:13:16 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com