如果您有以下代码:
j=3; // Line 1
i=6; // Line 2
i+=5; // Line 3
j=i--; // Line 4
...据我所知, j
的值将变成 6。如果是 --i
,那就是 5 等等。
但是如果我打印出 i
的值在第 4 行之后,我得到 10 而不是第 3 行的 11。
为什么会发生这种情况?这是否意味着如果我声明 i
是一个数字,稍后我返回代码并将另一个变量设置为 i--
,在我的大部分i's
之前在代码中,它更改了 i
的值全局范围?
最佳答案
在您的代码中,请参阅以下分步操作。
j=3; //Line 1, j ==3
i=6; //Line 2, i == 6
i+=5; //Line 3, i == i + 5 == 11
j=i--; // line 4, j == 11, i == 10, after this line.
详细来说,x += y
可以分解为 x = x + y
,就是这样。
关于后递减,副作用(递减)将在表达式求值后发生。因此,无论如何,在下一条语句之前,i
的值将会递减。
添加一些引用,来自 C11
,第 §6.5.2.4 章,
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).[....]
和
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).
请注意,预递减和后递减的差异仅在它们所使用的表达式内可见。从使用该变量的下一条指令的角度来看,它们都会给您相同结果(效果)。
关于c - 将变量设置为等于递减变量是否会更改该变量的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34313553/