减法和 post 立即递减时的混乱
confusion while subtracting and post decrementing at once
我卡在一个自减问题代码如下
#include <stdio.h>
int main()
{
int x = 4, y = 3, z;
z = x-- - y;
printf("%d %d %d\n",x,y,z);
return 0;
}
据我所知输出应该是 4 3 0
根据我对z值的解释如下:
首先,因为它是一个 post 递减,所以首先我们将从 x 减少 y 的值,即 4-3 等于 1,根据我的说法,我们将再次从这个 1 减少 1(或者我们不纠正如果我在这里错了,我就是我)并且输出将为 0.
表达式 x--
的计算结果为 x
的 当前 值,即 4。然后从中减去 y
的值结果为 1 的值是分配给 z
的值。
x
然后作为后递减的副作用递减。
所以输出将为 3 3 1。
来自 C 标准(6.5.2.4 后缀递增和递减运算符)
2 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.98)
3 The postfix -- operator is analogous to the postfix ++ operator,
except that the value of the operand is decremented (that is, the
value 1 of the appropriate type is subtracted from it).
因此在这个声明中
z = x-- - y;
在递减 4 之前使用变量 x 的值。因此 4 - 3
产生 1
。
但是对象 x 本身被递减了,在这条语句之后它的值变得等于 3。
因此您将得到以下输出
3 3 1
顺便说一下,您可以重写此语句
z = x-- - y;
喜欢 :)
z = x --- y;
我卡在一个自减问题代码如下
#include <stdio.h>
int main()
{
int x = 4, y = 3, z;
z = x-- - y;
printf("%d %d %d\n",x,y,z);
return 0;
}
据我所知输出应该是 4 3 0 根据我对z值的解释如下: 首先,因为它是一个 post 递减,所以首先我们将从 x 减少 y 的值,即 4-3 等于 1,根据我的说法,我们将再次从这个 1 减少 1(或者我们不纠正如果我在这里错了,我就是我)并且输出将为 0.
表达式 x--
的计算结果为 x
的 当前 值,即 4。然后从中减去 y
的值结果为 1 的值是分配给 z
的值。
x
然后作为后递减的副作用递减。
所以输出将为 3 3 1。
来自 C 标准(6.5.2.4 后缀递增和递减运算符)
2 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.98)
3 The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).
因此在这个声明中
z = x-- - y;
在递减 4 之前使用变量 x 的值。因此 4 - 3
产生 1
。
但是对象 x 本身被递减了,在这条语句之后它的值变得等于 3。
因此您将得到以下输出
3 3 1
顺便说一下,您可以重写此语句
z = x-- - y;
喜欢 :)
z = x --- y;