How does post-increment work in this case?

69 Views Asked by At
            int value = 10;
            value = value++ + --value;
            Console.WriteLine(value);

I already know the result, but I want to ask how correctly I understood the sequence of actions. Initially, value++ returns the current value, i.e. 10. In the next step, it will be incremented. After that, the priority is --value, here we subtract 1, it will be 9 and we write +1 from the previous value, that is, it will be 10 and the last action from left to right is 10 + 10, right? Or --value, 11 is stored immediately and 1 is subtracted from it? Which option is correct? Am I misunderstanding something?

1

There are 1 best solutions below

3
On

I think I see what the confusion is. This example may clear it up:

int value = 10;
value = value++;
Console.WriteLine(value);
// Output: 10

value = 10;
value = ++value;
Console.WriteLine(value);
// Output: 11

In the first block, the value is post-incremented. It is not updated, because we assign the value to its current value of 10, and then increment it (this does not set it or update the variable). In the 2nd block, the value is pre-incremented. So we increment the value first, and then assign the value after the increment, making the assigned value 11.

When we post-increment value in the above line (value++) we are saying that we are not going to update its value until after this operation. But the assignment is overwritten by the assignment we are making in this line. Now let's look at another example to illustrate:

int value = 10;
value = value++;
Console.WriteLine(value);
// Output: 10
value++;
Console.WriteLine(value);
// Output: 11

When we do value = value++, we are overwriting the assignment that would happen in the operator, and so it has no effect on the value.