# Learntofish's Blog

## Increment operator: difference between ++i and i++

Posted by Ed on November 22, 2011

The increment operator raises the value of an integer by 1:
Example in C++:

using namespace std;

int main(){
int i=5;

// increment
cout << "before: i=" << i << endl;
i++;
cout << "after: i=" << i << endl;

return 0;
}

The console output is:

before: i=5
after: i=6

The result is the same if we write ++i instead:

#include <iostream>

using namespace std;

int main(){
int i=5;

// increment
cout << "before: i=" << i << endl;
++i;
cout << "after: i=" << i << endl;

return 0;
}

The console output still is:

before: i=5
after: i=6

However, there is a difference as soon as we make an assignment:

Here, we declare a variable k and assign
a) i++ (post increment)
b) ++i (pre increment)

Case a) post increment

#include <iostream>

using namespace std;

int main(){
int i=5;
cout << "Value of i (before): " << i << endl;

// assign and increment
int k = i++;
cout << "Incrementing with i++ ..." << endl;
cout << "\nThe value of i is: " << i << endl;
cout << "The value of k is: " << k << endl;

return 0;
}

The console output is:

Value of i (before): 5
Incrementing with i++ ...

The value of i is: 6
The value of k is: 5

You will notice that i is incremented whereas k is not. The explanation is the following:
k = i++ actually consists of two steps:
(i) k = i (assignment)
(ii) i = i+1 (increment)
Here, we first assign and then increment.

Case b) pre increment
This time we will put the plus signs in front of i:

#include <iostream>

using namespace std;

int main(){
int i=5;
cout << "Value of i (before): " << i << endl;

// increment and assign
int k = ++i;
cout << "Incrementing with ++i ..." << endl;
cout << "\nThe value of i is: " << i << endl;
cout << "The value of k is: " << k << endl;

return 0;
}

The result is now different as shown by the console output:

Value of i (before): 5
Incrementing with ++i ...

The value of i is: 6
The value of k is: 6

You will notice that i is incremented and k has the incremented value! The explanation is the following:
k = ++i consists of two steps:
(i) i = i+1 (increment)
(ii) k = i (assign)
Here, since the two plus signs occur in front of i, we first increment and then assign the value to k.

I wasn’t aware of the difference until I wrote a recursive function (see last time) and got stuck in an endless loop. Basically I passed i++ to a function:

myFunction(i++)

As a result the incremented value was never passed to the function.