I have a very short question, but it really confused me.
var y = 3, x = y++;
What is the value of x?
I thought the answer should be 4, but actually it's 3.
Can anyone explain me the reason?
y++
is called post-increment -- it increments the variable after it returns the original value as the value of the expression. So
x = y++;
is equivalent to:
temp = y;
y = y + 1;
x = temp;
If you want to return the new value, you should use ++y
. This is called pre-increment because it increments the variable before returning it. The statement
x = ++y;
is equivalent to:
y = y + 1;
x = y;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With