Programming Puzzel For You All

Started by
41 comments, last by SiCrane 18 years, 6 months ago
Evaluate the following in your head:

#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;
}






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.
- GDKnight
Advertisement
9? In my head, no checking.
Interesting... Not 9.
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)


---CyberbrineDreamsSuspected implementation of the Windows idle loop: void idle_loop() { *((char*)rand()) = 0; }
Huh. I got 9 in my head as well, and then GCC says 10.

How did that happen?
Things change.
Modifying a variable several times in between code points has undefined behaviour.

int k = (++i)+(++i)+(++i); is neither valid C nor C++.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.
now that's just sloppy code.
Got 9 with J2SDK 1.4.2_06 and in my tiny head too which now hurts.
MacPro 2.66 GHz QuadCore, OS X 10.5, 5GB, Radeon x1900 and no more gray hair.http://www.spexlab.org

This topic is closed to new replies.

Advertisement