Java增量和赋值运算符
我对post ++和pre ++运算符感到困惑,例如在以下代码中
I am confused about the post ++ and pre ++ operator , for example in the following code
int x = 10;
x = x++;
sysout(x);
将打印10?
打印10,但我预计它应该打印11
It prints 10,but I expected it should print 11
但是当我这样做时
x = ++x; instead of x = x++;
它会按照我的预期打印11,所以为什么x = x ++;不改变x的值?
it will print eleven as I expected , so why does x = x++; doesn't change the the value of x ?
不,打印输出10是正确的。理解结果背后原因的关键是预增量 ++ x
和后增量 x ++
之间的差异复合作业。使用预增量时,表达式的值在执行增量后获取。但是,当您使用后递增时,表达式的值在递增之前取,并在将递增结果写回变量之后存储供以后使用。
No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x
and post-increment x++
compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.
以下是导致您所看到的事件序列:
Here is the sequence of events that leads to what you see:
-
x
被分配10
- 由于
++
在后增量位置,存储x
的当前值(即10
)供以后使用 - 新值
11
存储在x
-
10
的临时值存储回x
,写在上11
已存储在那里。
-
x
is assigned10
- Because of
++
in post-increment position, the current value ofx
(i.e.10
) is stored for later use - New value of
11
is stored intox
- The temporary value of
10
is stored back intox
, writing right over11
that has been stored there.