Java增量和赋值运算符 [英] Java increment and assignment operator

查看:159
本文介绍了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 assigned 10
  • Because of ++ in post-increment position, the current value of x (i.e. 10) is stored for later use
  • New value of 11 is stored into x
  • The temporary value of 10 is stored back into x, writing right over 11 that has been stored there.

这篇关于Java增量和赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆