Possible C compiler bug on 8086 machines

Kevin Johnson t-kevinj at microsoft.UUCP
Tue Jan 15 05:48:58 AEST 1991


In article <3577 at bruce.cs.monash.OZ.AU> alanf at bruce.cs.monash.OZ.AU (Alan Grant Finlay) writes:
...<some stuff deleted here>...
>   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);
...<more stuff deleted here>...
>And here is a sample output: 
>This works : 128, 512
>This doesn't work : 128, 0

In this case, 65536/512 is going to be considered a long value (remember
that an int is 16 bits and a long is 32 on the 8086).  In the first case 
(x = 65536/512 ;), the long is being typecast back to an int.  

In the printf statement, no typecasting is being done so the compiler
is pushing a long rather than an int.  When printf is trying to figure
out what you want to print, it grabs the low word of (65536/512) to
fit the first %d, and the high word (zero, in this case) to fit the
second %d.  The last word pushed (OK, technically the first one, but
that's irrelevant here) is the value 512, which is ignored by printf.

To fix this, typecast the 65536/512 in the printf to an int:
  printf ("This doesn't work : %d, %d\n", (int) 65536 / 512, 512) ;

Things will magically work...


--Kevin



More information about the Comp.lang.c mailing list