执行时(幕后)会发生什么?

int x = 7;
x = x++;

也就是说,当一个变量在一条语句中被递增并分配给自己时?我编译并执行了这个。即使在整个表述之后X仍然是7。在我的书里,它说x是递增的!


当前回答

根据从类文件中获得的Byte码,

这两种赋值都增加x,但不同之处在于将值压入堆栈的时间

在Case1中,Push发生在增量之前(然后稍后分配)(本质上意味着您的增量不做任何事情)

在Case2中,Increment首先发生(使其为8),然后压入堆栈(然后分配给x)

案例1:

int x=7;
x=x++;

字节代码:

0  bipush 7     //Push 7 onto  stack
2  istore_1 [x] //Pop  7 and store in x
3  iload_1  [x] //Push 7 onto stack
4  iinc 1 1 [x] //Increment x by 1 (x=8)
7  istore_1 [x] //Pop 7 and store in x
8  return       //x now has 7

案例2:

int x=7; 
x=++x;

字节码

0  bipush 7     //Push 7 onto stack
2  istore_1 [x] //Pop 7 and store in x
3  iinc 1 1 [x] //Increment x by 1 (x=8)
6  iload_1  [x] //Push x onto stack
7  istore_1 [x] //Pop 8 and store in x
8  return       //x now has 8

Stack在这里指的是操作数Stack, local: x index: 1 type: int

其他回答

x = x++;

等于

int tmp = x;
x++;
x = tmp;

X确实增加了。但是你把原来的x值赋回了自身。


x = x++;

x++增加X并返回其旧值。 X =将旧值赋回给自身。

最后,x被赋回了它的初始值。

++x为增量前-> x在使用前为增量 x++是后增量-> X在使用后递增

int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented

增量发生在x被调用之后,所以x仍然等于7。当调用x时,++x将等于8

它在“x = x++;”后面递增。如果你写x = ++x;它就是8。