怎么是x = 20; x = ++ x + ++ x + x ++; java中x的最终值是65 [英] how is that x=20;x= ++x + ++x + x++ ;final value of x in java is 65

查看:227
本文介绍了怎么是x = 20; x = ++ x + ++ x + x ++; java中x的最终值是65的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这怎么可能,因为后增量运算符应该将x增加到66?

how is this possible as post increment operator should increase x to 66?

当我为y = ++ x + ++ x + x ++做同样的事情时;它为y赋值65,为x赋值23。

When i did the same for y= ++x + ++x + x++; it gave a value 65 for y and 23 for x.

所以让我知道java编译器如何解决这些表达式。

So let me know how is java compilers solving these expression.

推荐答案

让Java给你看。 javap -c MyClass 显示字节码:

Let Java show you. javap -c MyClass shows you bytecode:

  public static void main(java.lang.String[]);
    Code:
       0: bipush        20
       2: istore_1      
       3: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       6: iinc          1, 1
       9: iload_1       
      10: iinc          1, 1
      13: iload_1       
      14: iadd          
      15: iload_1       
      16: iinc          1, 1
      19: iadd          
      20: dup           
      21: istore_1      
      22: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
      25: return        

如果你考虑它,结果是完全合乎逻辑的:你有两个前增量和一个后增量。所以,你的代码生效了:

And the result is completely logical if you think about it: you have two preincrements and one postincrement. So, your code is in effect:

y = 0

x++      // 21
y += x

x++      // 22
y += x

y += x   // (still 22!)
x++      // 23

x = y    // (21 + 22 + 22 at this point)

这篇关于怎么是x = 20; x = ++ x + ++ x + x ++; java中x的最终值是65的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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