|
| 1 | +## x=x++最终x等于多少? |
| 2 | +### 问题描述: |
| 3 | +``` |
| 4 | +public class Tests { |
| 5 | + public static void main(String[] args) throws Exception { |
| 6 | + int x = 0; |
| 7 | + while(x<3) { |
| 8 | + x = x++; |
| 9 | + System.out.println(x); |
| 10 | + } |
| 11 | + } |
| 12 | +} |
| 13 | +``` |
| 14 | +如上,程序会进入死循环,我们知道通常对于x自增是通过x++或者x=x+1,那么为什么x=x++不是对x自增再赋值给x? |
| 15 | + |
| 16 | +### 回答: |
| 17 | +明确x=x++处理流程,相当于: |
| 18 | +```java |
| 19 | +int temp=x; |
| 20 | +x++; |
| 21 | +x=temp; |
| 22 | +``` |
| 23 | +#### 解释: |
| 24 | +考虑如下类: |
| 25 | +```java |
| 26 | +class test { |
| 27 | + public static void main(String[] args) { |
| 28 | + int i=0; |
| 29 | + i=i++; |
| 30 | + } |
| 31 | +} |
| 32 | +``` |
| 33 | +通过运行反汇编: |
| 34 | +```bash |
| 35 | +$ javap -c test |
| 36 | +``` |
| 37 | +可以得到: |
| 38 | +```java |
| 39 | +Compiled from "test.java" |
| 40 | +class test extends java.lang.Object{ |
| 41 | +test(); |
| 42 | + Code: |
| 43 | + 0: aload_0 |
| 44 | + 1: invokespecial #1; //Method java/lang/Object."<init>":()V |
| 45 | + 4: return |
| 46 | + |
| 47 | +public static void main(java.lang.String[]); |
| 48 | + Code: |
| 49 | + 0: iconst_0 |
| 50 | + 1: istore_1 |
| 51 | + 2: iload_1 |
| 52 | + 3: iinc 1, 1 |
| 53 | + 6: istore_1 |
| 54 | + 7: return |
| 55 | +} |
| 56 | +``` |
| 57 | +以下来解释其中的助记符: |
| 58 | +* iconst_0: 常量0被push入栈。 |
| 59 | + |
| 60 | +* istore_1: 栈顶元素被pop出,然后存储在索引为1的局部变量也就是x内。 |
| 61 | + |
| 62 | +* iload_1 : 索引为1的局部变量(即x)的值被push入栈,此时栈顶值为0。 |
| 63 | + |
| 64 | +* iinc 1, 1 :索引为1的量增加为1,也就是x变为1。 |
| 65 | + |
| 66 | +* istore_1 : 栈顶值被pop出,存入索引为1的局部变量中,因此x再次变为0。 |
| 67 | + |
| 68 | +以上,可以知道x=x++由于入栈出栈,x的值并未变化。 |
| 69 | + |
| 70 | +#### 对比:x=++x |
| 71 | +```java |
| 72 | +class test { |
| 73 | + public static void main(String[] args) { |
| 74 | + int i=0; |
| 75 | + i=++i; |
| 76 | + } |
| 77 | +} |
| 78 | +``` |
| 79 | +运行 |
| 80 | +```bash |
| 81 | +$ javac test.java |
| 82 | +$ javap -c test |
| 83 | +``` |
| 84 | +得到: |
| 85 | +```java |
| 86 | +Compiled from "test.java" |
| 87 | +class test { |
| 88 | + test(); |
| 89 | + Code: |
| 90 | + 0: aload_0 |
| 91 | + 1: invokespecial #1 // Method java/lang/Object."<init>":()V |
| 92 | + 4: return |
| 93 | + |
| 94 | + public static void main(java.lang.String[]); |
| 95 | + Code: |
| 96 | + 0: iconst_0 |
| 97 | + 1: istore_1 |
| 98 | + 2: iinc 1, 1 |
| 99 | + 5: iload_1 |
| 100 | + 6: istore_1 |
| 101 | + 7: return |
| 102 | +} |
| 103 | +``` |
| 104 | +可以看出是先对x进行加一,再将x的值push入栈,随后再将栈顶值赋给x。 |
| 105 | + |
| 106 | + |
0 commit comments