post and pre increment operator

I came across this question in some interview site and I am wondering why the result is showing different on my compiler
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
using namespace std;

int main() {
    int i = 5;
	cout << "" << i++ + ++i << endl;
	cout << "" << i++ + ++i + i++ + i++ << endl;
	cout << ""<< ++i + i++ + ++i + i++ << endl;
}



12
32
52
Press any key to continue . . .


When I calculate I am getting output as 12, 35 and 52.
Normally it would be undefined behavior but I could have sworn that + created a sequence point.

This generates yet different output: http://ideone.com/yqOlxg

I'm guessing it's undefined despite the plusses.
The behavior of those expressions is undefined. The compiler is free to do anything at all when it encounters code like this. It can generate valid code, it can reject the program, it can crash. Anything.

The reason is simple: in what order do you execute i++ + ++i? For convenience, let's rename: i1++ + ++i2. All the standard says is that:
1. i1++ equals i1 before increment.
2. ++i2 equals i2 after increment.
3. i1++ and ++i2 have to be fully evaluated before + is.
Nothing is said about which operand will be evaluated first, or when the increments will be placed. For example, these are valid implementations:
1
2
3
4
temp = i1;
i2++;
i1++;
temp += i2;
1
2
3
4
i2++;
temp = i1;
temp += i2;
i1++;
1
2
3
4
i2++;
temp = i1;
i1++;
temp += i2;
But, like I said above, the compiler isn't forced to generate reasonable code like this, or even any code at all.
Topic archived. No new replies allowed.