Re: Style question: comparison between signed and unsigned?

Kai Henningsen (kaih@khms.westfalen.de)
25 Sep 1997 20:51:00 +0200


tytso@MIT.EDU (Theodore Y. Ts'o) wrote on 23.09.97 in <199709232326.TAA00806@dcl.MIT.EDU>:

> From: Ulrich Drepper <drepper@ipd.info.uni-karlsruhe.de>
> Date: 24 Sep 1997 00:03:11 +0200
>
> What I would like to see and which catches most cases I came across is
> that gcc does not warn in this case:
>
> ssize_t n = read (...);
> if (n < 0)
> ...
> else
> {
> if (n < sizeof (foo))
> ...
> }
>
> At least when optimizing gcc knows that when executing the second `if'
> the variable `n' cannot be negative and since
> sizeof(ssize_t)==sizeof(size_t) there is no reason for a warning.
>
> Actually, GCC can do better than that. 99.97% of the time, sizeof(foo)
> is less than 2**31, so as long as you do a signed comparison, the right
> thing will happen anyway. There's no need to any kind of flow analysis
> to figure this out!

Unfortunately, the C standard says that you MUST do an unsigned
comparision (if the signed type isn't larger than the unsigned one, as in
the above example).

Seems to me the compiler actually caught a bug in your understanding of C.

MfG Kai