post increment operator java [英] post increment operator java

查看:90
本文介绍了post increment operator java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过joshua bloch从java puzzlers中获取以下代码的正面或反面。

I can't make heads or tails of the following code from "java puzzlers" by joshua bloch.

public class Test22{
 public static void main(String args[]){
  int j=0;
  for(int i=0;i<100;i++){ 
    j=j++;
  }
  System.out.println(j); //prints 0

  int a=0,b=0;
  a=b++;
  System.out.println(a);
  System.out.println(b); //prints 1


 }
}

我无法得到j打印的部分0.
据作者说,

I can't get the part where j prints 0. According to the author,

j=j++

类似于

temp=j;
j=j+1;
j=temp;

但是

a=b++

使b 1.
因此它应该被评估像这样,

makes b 1. So it should've evaluated like this,

a=b
b=b+1

按照相同的逻辑,不应该

By following the same logic, shouldn't

j=j++

评估为,

j=j
j=j+1

这里的温度在哪里?
任何解释都将不胜感激。 <<我正在打破这个问题。 ;)>>
先谢谢。

Where does the temp come into picture here? Any explanations would be much appreciated. << I'm breaking my head over this. ;)>> Thanks in advance.

推荐答案

让我们分解你自己的论点:

Let's break down your own argument:


根据作者的说法,

According to the author,

j=j++;

类似于

temp=j;
j=j+1;    // increment
j=temp;   // then assign


是的,到目前为止你是对的。 ..,但是这里你错了:

Yes, you're right so far..., but here's where you got it wrong:


但是

But

a=b++;

使 b = 1 。所以它应该像这样评估,

makes b=1. So it should've evaluated like this,

a=b;      // assign
b=b+1;    // then increment


错误!你没有一贯地应用这条规则!您已从增量更改订单然后将分配给分配然后增加 !!!它的实际评估如下:

WRONG! You're not applying the rule consistently! You've changed the order from increment then assign to assign then increment!!! It's actually evaluated like this:

temp=b;
b=b+1;     // increment
a=temp;    // then assign

此表格的基本分配:

lhs = rhs++;

类似于这样的事情:

temp = rhs;
rhs = rhs+1;  // increment
lhs = temp;   // then assign

将此应用于 a = b ++; 。然后将它也应用于 j = j ++; 。这就是为什么你得到你得到的结果。

Apply this to a = b++;. Then apply it also to j = j++;. That's why you get the results that you get.

你做的是你提出了你自己的解释 a = b ++; 确实 - 不符合上述规则的错误解释。这是你混乱的根源。

What you did was you came up with your own interpretation of what a = b++; does -- a WRONG interpretation that doesn't follow the above rule. That's the source of your confusion.

  • JLS 15.14.2 Postfix Increment Operator

...将值1添加到变量的值中,并将总和存储回变量[ ...]后缀增量表达式的值是存储新值之前的变量的值。

"...the value 1 is added to the value of the variable and the sum is stored back into the variable [...] The value of the postfix increment expression is the value of the variable before the new value is stored."


这篇关于post increment operator java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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