0
Can anyone explain to me? What is the difference of ++x and x++, how do they work?
I don't get it x = 3 a = ++x //will print 4, but b = x++ //will print 3
7 Answers
+ 4
a = ++x
In this, first value of x is increased by 1 and then the increased value is assigned to a, Hence a =4
b = x++
In this. first value of x is assigned to b and then value of x is increased. Hence b = 3
+ 3
++x does x=x+1 then store value in x
x++ does x=x+1 but doesn't store value in x until the end of the line
+ 2
When I learned postfix and prefix, I found that it was easier with an example that prints out the value of your variable twice. Here is the code you can use to try it out for yourself. You can try out the code at: Ideone.com
Source code:
int a = 3;
int b = 3;
System.out.println("Postfix incrementation: ");
System.out.println(a++); // Prints a and increments with one
System.out.println(a++); // Prints a and increments with one
System.out.println("\nPrefix incrementation: ");
System.out.println(++b); // Inceremnts with one, then prints b
System.out.println(++b); // Inceremnts with one, then prints b
Output:
Postfix incrementation:
3
4
Prefix incrementation:
4
5
+ 1
Ooo, thanks a lot :)
+ 1
++x means increment by 1 and then assign the value.
x++ means return the acual value of x then increment it by 1 maybe for later use.
var a = 2
print(a++) //will print 2
print(a) //will print 3 to confirm that a is incremented now
var b = 2
print(++b) //will print 3
print(b) //will print 3 for sure.
+ 1
Thanks
0
++x increment first