Possible C compiler bug on 8086 machines
Michael Bryan
mbryan at netcom.UUCP
Sun Jan 13 05:02:44 AEST 1991
In article <3577 at bruce.cs.monash.OZ.AU> alanf at bruce.cs.monash.OZ.AU
(Alan Grant Finlay) writes:
[Program which gives unexpected results:]
>#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 problem is that in the printf statement, 65536/512 is a long integer,
and gets passed to printf as to 4 bytes, not 2. Your format control says
expect two 2-byte integers, so the higher-order bytes of the longword
get interpreted as the second integer, and they are zero. If you changed
your printf control to "%ld, %d", you would see the correct answer. (Or
perhaps more revealing, change it to "%d, %d, %d", to see "128, 0, 512"
printed.) Yet another alternative would be to cast the constant before
passing to printf, as in "(int)(65536/512)".
The reason is that the compiler sees 65536 as requiring a longword (max
short integer is 65535, unsigned), so the type of the constant 65536 is
a longword. The constant 65536/512 is a long divided by a short, which
will also have a type of long, due to C's type-conversion rules. The
reason "x = 65536/512" works is that the long constant "128" is converted
back to a short integer before storing the value in "x". The first call
to printf then passes two bytes for "x", and it prints as expected.
As far as I know, this is completely proper behaviour for C. I'm not
sure if all 16-bit integer versions of C behave exactly this way, but
any I've seen do.
--
Mike Bryan (mbryan at netcom, {claris,apple}!netcom!mbryan)
W:408/733-6565 H:408/738-2479 Sunnyvale, CA
"Does this sentence remind you of Agatha Christie?"
More information about the Comp.lang.c
mailing list