#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int i = 1;
int k = (++i)+(++i)+(++i);
cout << k << endl;
return 0;
}
Programming Puzzel For You All
Evaluate the following in your head:
Then evaluate the same thing in any compiler of your choice and check the output.
Post what you thought and what you got, along with compiler used. [grin]
Feel free to try other languages as well, this is quite intresting.
I thought I was going to get 9 and I got 12 with VS 2003 and 10 with g++ (GCC) 3.3.5 (Debian 1:3.3.5-13)
Modifying a variable several times in between code points has undefined behaviour.
int k = (++i)+(++i)+(++i); is neither valid C nor C++.
int k = (++i)+(++i)+(++i); is neither valid C nor C++.
One would hope that would generate an error or at least a warning if it's not valid C/C++...
Quote:Original post by MauMan
I thought I was going to get 9 and I got 12 with VS 2003 and 10 with g++ (GCC) 3.3.5 (Debian 1:3.3.5-13)
That is because it is undefined behaviour.
you could do this,
i=1;i+=i++++i++i+i++i++;
And the result would be different from compiler to compiler.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement