"C" the intracacies

Sunday, May 30, 2010

The other day, one of my nerdy mates, Rajdeep had put forth this problem, which caught me on the back foot. Apparently, the problem appealed like a fundamental predict the output snippet, but the exact reasoning is yet to be found. Following is the code snippet with some steps, someone needs the explain the reason behind such a weird output.

//File name: googly.c
#include
int main()
{
int a,b;
a=((b=5)+1); //Line 2
printf("a=%d b=%d",a,b);
return 0;
}

As you would have expected Line 2 essentially reduces to two sequential statements, b=5 and then a=b+1 and you get the result 'a'=6 and 'b'=5;

Now try replacing Line 2 with the expression a=((b=5)++)and then try to compile using a standard C compiler and you would observe an compilation error. You might come across a logic to explain that error.

But the strange behavior doesn't end here, save the code with a .cpp extension, compile it with a standard C++ compiler & you'd be startled to note that the error is gone and the program runs seamlessly to produce the output as a='5' and b='6'.

I suppose there's some compilation issue that makes it happen, but need a succinct logical explanation to this. Your reasonings are awaited...

Read more...

  © Blogger templates Newspaper by Ourblogtemplates.com 2008

Back to TOP