Wednesday, February 01, 2006

The small big problem..

Learning C from 2nd Sem.. Thought can explain the basics.. But when I tried to explain a very basic code to the first years in college, I was clean bowled.
The code:
#include
int main()
{
int i=5;
printf ("\n%d %d %d\n",i,i--,++i);
}
According to my knowledge it should give 5 6 6.
But it gave 5 6 5.. Why? I don't know... today in office, me,naresh & Arvind tried to figure out what is happening..
It is giving 5 6 6 up to GCC 4.0.0 version (as informed by Monuda), but in GCC 4.0.2 .. we can't explain the result..
Any one help me......................

6 Comments:

At 9:49 AM, Anonymous Anonymous said...

:) this is a bug in gcc!

I compiled the same code in gcc 4.0.2 and gcc 3.2.3

gcc 3.2 returned 5 6 6 as expected, while gcc 4.0.2 returned 5 6 5.

Damn Strange.

 
At 10:50 AM, Anonymous Anonymous said...

Here's a clue: think about how the stack is implemented(clue: lifo and fifo)

 
At 10:04 PM, Anonymous Anonymous said...

GCC 4.0 doesn't always use stack for passing arguments.

x86 ABI can use registers to pass func args.

Probably you should compile your code with

gcc -S test.c

and post the .s files it generates in both cases. I can probably explain what the assembly does :)

 
At 1:40 AM, Anonymous Anonymous said...

printf ("\n%d %d %d\n",i,i--,++i);

You are modifying the same element more than one time in the same statement. The result of this is undefined.

This is _NOT_ a GCC bug.

 
At 3:32 PM, Blogger Philip said...

read up on sequence points in the C/C++ specs. This is working correctly as designed for all implementations of C/C++

 
At 12:57 AM, Blogger Susam Pal said...

It's not a GCC bug.

It's quite obvious that program would give different results on different compilers.

printf ("\n%d %d %d\n",i,i--,++i);

The above statement is undefined and shouldn't be written in a C program.

Why?

The semi-colon is the only sequence point. You are modifying the value of i twice before the next sequence point.

C guarantees that all side effects of a given expression will be completed by the next sequence point in the program.

What happens if there are two statements with side effects affecting each other occurs before the next sequence point, is left undefined in the C standard.

Hence you can not predict the result of that code.

Even if some compiler produces an output like: 157, 190, 111, you can't blame the compiler. Its undefined after all.

To write such code with undefined features is a blunder many neophyte programmers commits.

 

Post a Comment

<< Home