Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!caen!uwm.edu!linac!att!ucbvax!dog.ee.lbl.gov!elf.ee.lbl.gov!torek From: torek@elf.ee.lbl.gov (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Signed to unsigned comparison Message-ID: <11389@dog.ee.lbl.gov> Date: 24 Mar 91 01:16:47 GMT References: <40472@cup.portal.com> Reply-To: torek@elf.ee.lbl.gov (Chris Torek) Organization: Lawrence Berkeley Laboratory, Berkeley Lines: 44 X-Local-Date: Sat, 23 Mar 91 17:16:47 PST In article <40472@cup.portal.com> PLS@cup.portal.com (Paul L Schauble) writes: >What should a compiler do with the comparison in this example: > > unsigned int a = 5; > (a > -1) .... > >... the comparison should always be true ... >Correct? Does the standard address this case? No, and yes. The comparison of an unsigned and a signed is done by widening both to a `common' type; the result is that unsigned short a = 5; (a > -1) is true only if sizeof(short) < sizeof(int). If sizeof(short) == sizeof(int), the `common' type is unsigned and (for a typical 2s complement 32 bit machine) we get: (unsigned)5 > (unsigned)-1 0x00000005 > 0xfffffffe 0 If sizeof(short) < sizeof(int), the `common' type is int and we get: (int)5 > (int)-1 5 > -1 1 This is why the `unsigned preserving' semantics were the correct choice. ANSI C uses the `value preserving' semantics to attempt to make the comparison (unsigned short)5 > -1 less surprising---had they chosen unsigned-preserving semantics, it would *always* be false---but the result is that you can never predict what your programs will do; you are forced to include a cast. (A proper cast gives predictable results under both schemes.) Note that this particular botch affects you only if you have an uncast signed/unsigned comparison. -- In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427) Berkeley, CA Domain: torek@ee.lbl.gov