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

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

    A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:

    // original code
    int x = 7;
    x = x++;
    

    Let's rewrite this to do the same thing, based on removing the ++ operator:

    // behaves the same as the original code
    int x = 7;
    int tmp = x; // value of tmp here is 7
    x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
    x = tmp; // oops! we overwrote y with 7
    

    Now, let's rewrite it to do (what I think) you wanted:

    // original code
    int x = 7;
    x++;
    

    The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:

    for(int i = 0; i < 10; i++)
    {
        System.out.println(i);
    }
    

    Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:

    for(int i = 0; i < 10; i = i + 1)
    {
        System.out.println(i);
    }
    

    I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.

提交回复
热议问题