Re: [IDEA+RFC] Possible solution for min()/max() war

Patrick J. LoPresti (patl@cag.lcs.mit.edu)
30 Aug 2001 18:42:10 -0400


"Peter T. Breuer" <ptb@it.uc3m.es> writes:

> "Linus Torvalds wrote:"
> > What if the "int" happens to be negative?
>
> if sizeof(typeof(a)) != sizeof(typeof(b))
> BUG() // sizes differ
> const (typeof(a)) _a = ~(typeof(a))0
> const (typeof(b)) _b = ~(typeof(b))0
> if _a < 0 && _b > 0 || _a > 0 && b < 0
> BUG() // one signed, the other unsigned
> standard_max(a,b)

This is a MUCH nicer solution. max() is a well-defined mathematical
concept; it is simply the larger of its two arguments, period. It is
C's *promotion* rules that kill you, especially signed->unsigned
promotion. So just forbid them, at least when they implicit.

You can argue about whether the "differing sizes" case should be a
BUG(), since the output will still be mathematically correct. It
depends on how often it is useful to compare (say) unsigned chars
against ints, and on whether the compiler warns about cases where you
try to stuff the return value into a too-small container. I bet that
just forbidding signed->unsigned promotion would be enough.

In general, types should work for the programmer, not the other way
around. Force people to "think hard" about their types when they are
making a likely mistake, not *every* time they call max().

Littering all those calls with types is just gross.

- Pat
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/