Re: Style question: comparison between signed and unsigned?

Bodo Moeller (Bodo_Moeller@public.uni-hamburg.de)
Wed, 24 Sep 97 21:57 GMT+0200


smurf@noris.de (Matthias Urlichs):

>> /* check that we got a valid packet */
>> if (i < sizeof(struct pkthdr))
>> return SHORT_PACKET;

>> [...] gcc will [...] warn [...] because "i" is signed, but "sizeof"
>> is unsigned.

> And because GCC knows how to figure out the size of the struct, but then
> forgets to check if the high bit of that size is set (otherwise you cannot
> run into a problem in the first place). ^^^^^^
^^^^^^^^^^^^^^^^^^

Yes, you could run into problems. sizeof(...) has unsigned type
size_t, while i is a signed int. Thus the comparison
(i < sizeof(struct pkthdr))
is equivalent to
((size_t) i < sizeof(struct pkthdr)),
unless there was some clandestine change of the C standard. Here, the
problem is not that sizeof(...) is converted to signed int, but
that i is converted to an unsigned type. This could lead to undesired
consequences if we hadn't already handled the case i < 0.

> In other words, that warning _is_ a compiler bug.

No, it isn't. (If the compiler had decided _not_ to warn about that
implicit conversion because "the user knows what he's doing", _that_
clearly would have been a bug in your case :-)

Bodo M"oller
<Bodo_Moeller@public.uni-hamburg.de>