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

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

其他回答

根据从类文件中获得的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

int x = 7;
x = x++;

它在C和Java中有未定义的行为,请参阅这个答案。这取决于编译器发生了什么。

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

当int x = 7;X = X ++;?

Ans - >x++表示首先使用x的值作为表达式,然后将其增加1。 这就是你的情况。RHS上的x的值被复制到LHS上的变量x,然后x的值增加1。

类似地,++x表示->先将x的值加1,然后在表达式中使用。 在这个例子中,如果x = ++x;// where x = 7 你会得到8的值。

为了更清楚,请尝试找出有多少printf语句将执行以下代码

while(i++ <5)   
  printf("%d" , ++i);   // This might clear your concept upto  great extend

因为x++在将值赋值给变量后会增加值。 因此,在执行这一行时:

x++;

变量x仍然有原始值(7),但是在另一行再次使用x,例如

System.out.println(x + "");

结果是8。

如果您想在赋值语句中使用x的递增值,请使用

++x;

这将使x增加1,然后将该值赋给变量x。

(编辑) 不是x = x++,而是x++;前者将x的原始值赋给自己,所以它实际上在这一行上什么也不做。