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

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

    because x++ increments the value AFTER assigning it to the variable. so on and during the execution of this line:

    x++;
    

    the varialbe x will still have the original value (7), but using x again on another line, such as

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

    will give you 8.

    if you want to use an incremented value of x on your assignment statement, use

    ++x;
    

    This will increment x by 1, THEN assign that value to the variable x.

    [Edit] instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.

提交回复
热议问题