[Insight-developers] Comparing signed and unsigned

Paul Hughett hughett@mercur.uphs.upenn.edu
Tue, 9 Jan 2001 15:20:11 -0500


I have been looking over the Build Logs and have noticed that there
are many warnings about comparisons between signed and unsigned types.
Some of you may need reminding that this is often a BAD idea.  The
canonical example is this: Suppose that u1 is an unsigned long and and
has the value 2.  Then the result of the comparison `u1 > -1 ' is
false rather than the true you would expect; this happens because -1
is coerced to the unsigned value 2^n-1 before the comparison is done.
Similarly, if u1 and u2 are unsigned variables, then u1-u2 and u2-u1
are _both_ positive or zero.  You can get a properly signed value by
casting both to signed before subtracting, but this risks overflow if
u1, u2, or their difference is too large.

The moral of this story is:  Don't mix signed and unsigned unless you
really know what you're doing.

My own practice is to consistently use (signed) long for counts,
sizes, etc, unless I really, really need that extra bit of range AND
am prepared to deal with the possible overflows.  I usually use
unsigned only when I need a set of bits that I can apply the bitwise
boolean operators to.


Changing the topic slightly: Is there any reason NOT to have -Wall as
the default warning level when gcc is used?  Then this error (and
others) would be flagged whenever you compile.


Paul Hughett