+ 1
C++ Incrementing
Can someone explain the difference between x++; and ++x; I know the first is post increment is the second is pre increment but I'm not sure how their is a difference. Could someone explain using numbers other than 1 and 2 to further assist me? Any help would be greatly appreciated!! thank you.
8 Answers
+ 4
x++ post increment, first evaluate then increment
++x pre increment, first increment then evaluate
+ 3
the best to explain it is if you use those inside of if statements or loops or when you print them
for example
int a = 3;
cout << ++a; // prints 4 because the ++ in front means it does the incrementation directly
cout << a++; // prints 3 because the ++ is after it and that means that it will be done after the statement is executed, in functions the postfix incrementation is done at the end of the function
+ 2
It's not difficult,
in the first case you use the variable and than you increment it
for example:
x = 0;
a = x++;
now:
a is 0 (the value of x before the increment)
and x is 1 (because you have incremented it with "++" )
In the second case instead, you increment the variable before use it,
for example
x = 0;
a = ++x;
now:
x is 1 (because you have incremented it) and
a is 1 (the value of x after the increment)
I hope I've helped you :)
p.s. Sorry if my English is not very good, it's not my language.
+ 1
Devender Mahajan Is incrementing in Java and C++ the same?
+ 1
Yes it same in C++ and Java. Sorry for delayed response.
0
"Devender Mahajan Is incrementing in Java and C++ the same?"
yes, it is ;)
0
x++ post increment, first evaluate then increment
++x pre increment, first increment then evaluate
-----
This is thw best answer by Clau.