"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...

1 comments:

Romi Banerjee said...

Hmmmmm well.... Likely that the clue to the answer lies in the precedence of the operators [thus giving the second answer], and the variable requirement stringency differences between the C compiler and the CPP compiler....

Remember the stack operator handling phenomenon??.... Taking cue from this stack operation :


The actual CPP execution steps may be summarized as....

void main()
{
int a, b;
b = 5;
a = b++;
}



While in C, the above steps turn into,

void main()
{
int a, b;
b = 5;
a = 5++; ['b' gets substituted by '5' and thus, the lvalue error]
}

The aforementioned fact gives a glimpse of the CPP compiler coding - where operator handling is concerned.... there perhaps might be two data structures - one a normal stack holding the requisite operators (the normal fashion), and perhaps another unit that holds variables recently handled (or perhaps a pointer to the variable in the symbol table - indicating the variable most recently used - thus allowing the above operation sequence).... In fact, this even suggests that the symbol table's definitely got an indexed search mechanism..... or perhaps the compiler uses a structure akin a cache to handle such.....

Does the above explanation look valid [:P]??......

  © Blogger templates Newspaper by Ourblogtemplates.com 2008

Back to TOP