6 ????

Hello,
Why the following code result is 6?


#include <iostream>
#include <conio.h>
using namespace std;
int main () {
int i=1;
i=(++i)+(++i);
cout<<i;
getche();
return 0;
}
The result of the expression in undefined. It could be 6 just as well as it could be -138300.

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15
Last edited on
So true(the link by helios).

But can't we guess what algorithm, the system must have followed to get a '6'?
+1 helios.


@SameerThigale
Looks like it did this:

1
2
3
4
int i = 1;
++i; // 2
++i; // 3
i = i + i;  // 6 
Yupp,
evaluate the parentheses then add them up.
But just to reiterate what helios is saying... the compiler doesn't have to do it that way.

The compiler could do it like this and it would still be perfectly valid:

1
2
3
4
5
int i = 1;
++i;  // i = 2
int temp = i;  // temp = 2
++i;  // i = 3
i = temp + i; // i = 5 


hence why this behavior is undefined and you shouldn't do this.
Topic archived. No new replies allowed.