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

后端 未结 17 1347
佛祖请我去吃肉
佛祖请我去吃肉 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:33

    It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".

    0 讨论(0)
  • 2020-11-21 06:38
    int x = 7;
    x = x++;
    

    It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.

    0 讨论(0)
  • 2020-11-21 06:38

    So this means: x++ is not equal to x = x+1

    because:

    int x = 7; x = x++;
    x is 7
    
    int x = 7; x = x = x+1;
    x is 8
    

    and now it seems a bit strange:

    int x = 7; x = x+=1;
    x is 8
    

    very compiler dependent!

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-21 06:41

    When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do

    x++; // don't re-assign, just increment
    System.out.println(x); // prints 8
    
    0 讨论(0)
  • 2020-11-21 06:41

    I think this controversy can be resolved without going into code & just thinking.

    Consider i++ & ++i as functions, say Func1 & Func2.

    Now i=7;
    Func1(i++) returns 7, Func2(++i) returns 8 (everybody knows this). Internally both the functions increment i to 8 , but they return different values.

    So i = i++ calls the function Func1. Inside the function i increments to 8, but on completion the function returns 7.

    So ultimately 7 gets allocated to i. (So in the end, i = 7)

    0 讨论(0)
提交回复
热议问题