What is the difference between ++i and i++?

I'm not really sure what the difference is and when to use which one. I know that ++i increments i before processing the current statement and i++ processes if after but I'm still kinda confused. Why do I get different results on each of these for loops?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
    cout << "first loop \n";
    for (int i = 0; i < 10; i++) cout << i << endl; //prints 0-9
    
    cout << "second loop\n";
    for (int i = 0; i++ < 10;) cout << i << endl; //prints 1-10
    
    cout << "third loop\n";
    for (int i = 0; ++i < 10;) cout << i << endl; //prints 1-9
    
    return 0;
}


I really appreciate any help. Thanx :)
Perhaps you really need to know more about how the loop is executed, and at what stage the comparison is done and the value incremented.
http://www.cplusplus.com/doc/tutorial/control/
In the first loop incrementing of i is being done after the current value of i will be displayed.
In the second and third loops i is being incremented and only after that it is displayed.
Last edited on
The behaviour of comparing, incrementing and printing are different for these 3 loops. Below is the order of those behaviour in each loop.

first loop --> compare, print and increment

second loop --> compare, increment and print

third loop --> increment, compare and print.
Topic archived. No new replies allowed.