Xref: utzoo comp.lang.c:35171 comp.os.msdos.programmer:2801 Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!wuarchive!julius.cs.uiuc.edu!apple!netcom!mbryan From: mbryan@netcom.UUCP (Michael Bryan) Newsgroups: comp.lang.c,comp.os.msdos.programmer Subject: Re: Possible C compiler bug on 8086 machines Message-ID: <20722@netcom.UUCP> Date: 12 Jan 91 18:02:44 GMT References: <3577@bruce.cs.monash.OZ.AU> Organization: Netcom- The Bay Area's Public Access Unix System {408 241-9760 guest} Lines: 42 In article <3577@bruce.cs.monash.OZ.AU> alanf@bruce.cs.monash.OZ.AU (Alan Grant Finlay) writes: [Program which gives unexpected results:] >#include >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@netcom, {claris,apple}!netcom!mbryan) W:408/733-6565 H:408/738-2479 Sunnyvale, CA "Does this sentence remind you of Agatha Christie?"