What is x after “x = x++”?

后端 未结 17 1358
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:26

What happens (behind the curtains) when this is executed?

int x = 7;
x = x++;

That is, when a variable is post incremented and assigned to

17条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 06:41

    According to Byte code obtained from the class files,

    Both assignments increment x, but difference is the timing of when the value is pushed onto the stack

    In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)

    In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)

    Case 1:

    int x=7;
    x=x++;
    

    Byte Code:

    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
    

    Case 2:

    int x=7; 
    x=++x;
    

    Byte Code

    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 here refers to Operand Stack, local: x index: 1 type: int

提交回复
热议问题