PLEASE HELP

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:17pm
n++ takes the value of n and then increments it.
++n increments the value of n and then takes its value.

So:
1
2
3
4
5
int n=3;
int p=n++; //now n is 4 and p is 3

int n=3;
int p=++n; //now n is 4 and p is 4 


Note that due to the way post-increment works, it generally leads to the creation of a temporary object when used on class instances.
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.
Topic archived. No new replies allowed.