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

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

    Post Increment operator works as follows:

    1. Store previous value of operand.
    2. Increment the value of the operand.
    3. Return the previous value of the operand.

    So the statement

    int x = 7;
    x = x++; 
    

    would be evaluated as follows:

    1. x is initialized with value 7
    2. post increment operator stores previous value of x i.e. 7 to return.
    3. Increments the x, so now x is 8
    4. Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7

    So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.

提交回复
热议问题