+ 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.
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.
+ 3
x = 2
y = ++x
z = x++
y = 3.
z = 2.
+ 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.
+ 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.
+ 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.
+ 1
@bagshot
They both equal 3.
+ 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.
0
do you have an example please bagshot? i lost a game becuase of this lol