Jan 17, 2012 at 5:56pm
I've been programming in C++ for a few months now but I still don't quite understand the difference between the following C++ statement.
n++;
++n;
n--;
--n;
assuming the variable n is declared and initialized. Please help?
Jan 17, 2012 at 6:18pm
The simple difference is:
++n add +1 to its value and then do some operation
n++ do some operation and then add +1 to its value
Example:
1 2 3 4 5 6 7
|
int x = 4;
cout << x++ << endl; // prints: "4"
// x is equal to 5 now
int y = 4;
cout << ++y << endl; // prints: "5"
// y is equal to 5 now
|
++n says "Add +1 and then do that"
n++ says "Do that and then add +1"
Last edited on Jan 17, 2012 at 6:20pm
Jan 18, 2012 at 6:57pm
I always use the pre-increment and decrement. (++n, --n)
because no temporary object is created it should be faster.