+ 2

Is there an easy way to remember the difference between x++ and ++x?

I just started learning java and always confuse ++x with x++. It is very difficult to remember which one did what and how they can be used.

20th Jul 2017, 8:53 PM
Robin Liu
8 Antworten
+ 4
Look at the position of ++ in relation to x. In ++x the plus signs are before the x, so you plus 1 before you pass the value. In x++ the plus signs are after the x, so you plus 1 after you pass the value.
20th Jul 2017, 8:58 PM
James
James - avatar
+ 3
x = 2 y = ++x z = x++ y = 3. z = 2.
20th Jul 2017, 9:08 PM
Bagshot
Bagshot - avatar
+ 2
Yeah, if the value is first (x++) then assign the value before incrementing; if the increment is first (++x) then increment before assigning the value.
20th Jul 2017, 8:56 PM
Bagshot
Bagshot - avatar
+ 2
Soz, I really meant to say you need to test them seprately. Test this first in code playground: int x = 2; int y = x++; Console.WriteLine(y); This will output 2. Now test this second: int x = 2; int y = ++x; Console.WriteLine(y); This will output 3.
20th Jul 2017, 9:36 PM
Bagshot
Bagshot - avatar
+ 2
I fear I may have confused the issue with my rather poor first example. Honestly, it's really not that difficult once you get your head around it. Just remember that ++x means increment first then assign value; and x++ means assign value first then increment.
20th Jul 2017, 9:53 PM
Bagshot
Bagshot - avatar
+ 1
@bagshot They both equal 3.
20th Jul 2017, 9:14 PM
James
James - avatar
+ 1
Once you understand it, it shouldn't be difficult to memorize by the name: x++ is called "postfix" "post" means AFTER. ++x is called "prefix" "pre" means BEFORE. You can think of it as being before/after doing the operation.
20th Jul 2017, 10:12 PM
Rrestoring faith
Rrestoring faith - avatar
0
do you have an example please bagshot? i lost a game becuase of this lol
20th Jul 2017, 8:58 PM
D_Stark
D_Stark - avatar