Signed to unsigned comparison

Chris Torek torek at elf.ee.lbl.gov
Sun Mar 24 11:16:47 AEST 1991


In article <40472 at cup.portal.com> PLS at 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 at ee.lbl.gov



More information about the Comp.lang.c mailing list