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>
usingnamespace 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;
}
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.