• Advertisement
Sign in to follow this  

Programming Puzzel For You All

This topic is 4578 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
9? In my head, no checking.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Interesting... Not 9.

Share this post


Link to post
Share on other sites
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)


Share this post


Link to post
Share on other sites
Modifying a variable several times in between code points has undefined behaviour.

int k = (++i)+(++i)+(++i); is neither valid C nor C++.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
One would hope that would generate an error or at least a warning if it's not valid C/C++...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement