I am confused about the post ++ and pre ++ operator , for example in the following code
int x = 10;
x = x++;
sysout(x);
will print 10 ?
It prints 10,but I expected it should print 11
but when I do
x = ++x; instead of x = x++;
it will print eleven as I expected , so why does x = x++; doesn't change the the value of x ?
The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way. Follow this answer to receive ...
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.
There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in that they can be written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix increment/decrement. The meaning is different in each case.
JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.
No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x
and post-increment x++
compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.
Here is the sequence of events that leads to what you see:
x
is assigned 10
++
in post-increment position, the current value of x
(i.e. 10
) is stored for later use11
is stored into x
10
is stored back into x
, writing right over 11
that has been stored there.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