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

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

    0 讨论(0)
  • 2020-11-21 06:54

    x does get incremented. But you are assigning the old value of x back into itself.


    x = x++;
    
    1. x++ increments x and returns its old value.
    2. x = assigns the old value back to itself.

    So in the end, x gets assigned back to its initial value.

    0 讨论(0)
  • 2020-11-21 06:58

    The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called

    0 讨论(0)
  • 2020-11-21 06:58

    What happens when int x = 7; x = x++;?

    ans -> x++ means first use value of x for expression and then increase it by 1.
    This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.

    Similarly ++x means -> increase the value of x first by one and then use in expression .
    So in your case if you do x = ++x ; // where x = 7
    you will get value of 8.

    For more clarity try to find out how many printf statement will execute the following code

    while(i++ <5)   
      printf("%d" , ++i);   // This might clear your concept upto  great extend
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题