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

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

    This is because you used a post-increment operator. In this following line of code

    x = x++;
    

    What happens is that, you're assigning the value of x to x. x++ increments x after the value of x is assigned to x. That is how post-increment operators work. They work after a statement has been executed. So in your code, x is returned first after then it is afterwards incremented.

    If you did

    x = ++x;
    

    The answer would be 8 because you used the pre-increment operator. This increments the value first before returning the value of x.

提交回复
热议问题