I was having a conversation about the prefix increment operator, and we seem to have run into a disagreement.
When running this code:
var x = 0;
x = ++x;
is the second line equivalent to:
- x = (x = x + 1) OR
- x = (x + 1)
It is hard to tell the difference because the results are identical (both result in x having a value of 1)
I believe that the value is not saved to the original variable when the left hand side of the assignment is the variable itself.
My counterpart disagrees and thinks the value is saved to the original variable whenever the ++ operator is used.
Which one of us is right?
It is saved, so it is similar to the first example.
Take for example this code:
That is because this will translate to:
Or, to be more accurate:
Why?
++vwill first save the incremented value of v, then it will return this incremented value.To simplify things, try this in your console:
If
++xwould resolve tox + 1, the value ofxwould now still be0, right?Nope, your
xwill be1. This means that++xmust have a assignment operator in there.