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

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

    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)

提交回复
热议问题