Possible C compiler bug on 8086 machines
Linus Torvalds
torvalds at cs.Helsinki.FI
Sat Jan 12 21:26:20 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
>
>Does anyone have any idea why?
>Is this a problem with my machine or the printf routine?
This is NOT a bug, but a programming error :-). The 65536 is implicitly
converted to a long (ie 65536L), as it doesn't fit into a int on the
8086 (all 8086 c-compilers I've used use 16-bits ints, but on a 32 bit
int machine this works as "expected"). Thus 65536/512 is a LONG, not an
int and is sent to printf as such. The reason 'x=65536/512;printf(..,x,)
works is that 65536/512 is (implicitly) converted to an int by the
assignment into x.
The code works if you change the second printf to:
printf("%d %d",(int) (65536/512),512); or alternately:
printf("%ld %d",65536/512,512);
NOTE! Please make 65536 EXPLICITLY long by using 65536L, this makes the
code much clearer and portable. (or don't use machines with a 16 bit int
:-)
Linus "mostly wrong" Torvalds
torvalds at cs.helsinki.fi
More information about the Comp.lang.c
mailing list