Pre-increment and post-increment (unusual behaviour, why and how?)

What will be the output of this piece of code?
It really made me curious how is that possible ?

for(int i=0; i<10; i++)
{
cout <<i<<endl;
cout << ++i<<" "<<i++<<endl;
cout <<i<<endl;
}
Output is undefined. What you're doing is illegal.

The general rule is you cannot modify a variable more than once in the same sequence point (ie: a semicolon). Since you are modifying the variable twice in the same semicolon, you will get unexpected results.

On the other hand...

1
2
3
4
5
6
7
for(int i=0; i<10; i++)
{
    cout <<i<<endl;
    cout << ++i <<" ";
    cout << i++ <<endl;
    cout <<i<<endl;
}


This will print the following
1
2
3
4
5
6
7
8
9
10
11
12
0
1 1
2
3
4 4
5
6
7 7
8
9
10 10
11
Topic archived. No new replies allowed.