Possible C compiler bug on 8086 machines

Bob Eager cur022%cluster at ukc.ac.uk
Tue Jan 15 19:22:12 AEST 1991


In article <3577 at bruce.cs.monash.OZ.AU>, alanf at bruce.cs.monash.OZ.AU (Alan Grant Finlay) writes:
> The following program demonstrates a printf that doesn't seem to work
> properly when compiled using a variety of C compilers for an 8086 machine.
> The program is as follows:
> -----------------------------//---------------------------
> 
> #include <stdio.h>
> 
> main()
> {
>    int x,y;
>    x = 65536/512;
>    y = 512;
>    printf("This works : %d, %d\n",x,y);
>    printf("This doesn't work : %d, %d\n",65536/512,512);
> }
> 
> ----------------------------//------------------------------
> 
> And here is a sample output: 
> 
> This works : 128, 512
> This doesn't work : 128, 0
> 

The compiler sees the 65536 in the second printf, and says: "This can't be
represented in an int, I need a long". I wonder if the 'rules' say that
it has to do this; certainly for an expression involving variables, the
presence of a long in an expression coerces the whole expression to long.

Given the above, it is easy to see what is happening. A four byte item is
pushed on the stack when printf is called: this represents 6655536/512 as a
long. The lower two bytes (the first ones on an 80x86) will contain the 128,
and are processed correctly. The second two bytes will be zero, and are
printed as the second value.

I bet if you change the first %d to %ld in the second printf, the expected
answer will appear!
-------------------------+-------------------------------------------------
Bob Eager                | University of Kent at Canterbury
                         | +44 227 764000 ext 7589
-------------------------+-------------------------------------------------



More information about the Comp.lang.c mailing list