Re: Style question: comparison between signed and unsigned?

Ulrich Drepper (drepper@ipd.info.uni-karlsruhe.de)
24 Sep 1997 16:29:16 +0200


torvalds@transmeta.com (Linus Torvalds) writes:

> There is nothing at all wrong with
>
> int n = read(...);
>
> within the context posted.

There is nothing wrong if you take a given situation. But in generic
code it is wrong. If I write a library and on a system with 32bit
ints and 64bit size_t (or 16/32 bits) I can run into severe problems.

> For example, take the following piece of code:
>
> int i;
> char * buf;
>
> while ((i = getchar()) != EOF) {
> *buf = i;
> buf++;
> }
>
> Are you suggesting that the compiler warn about the fact that you assign
> a "int" value into a "char"? You're losing information there - possibly
> a LOT of information. Do you want people to add a cast here too?

No, and the compile does not expect this as well. `char' is handled
special just because of these quirks in the language definition.

> AND for the same reason it is also completely correct to do
>
> if (n == -1)
> return -1;
>
> if (n < sizeof(struct pkthdr))
> return SHORT_PACKET;
> ...
>
> Essentially, if the compiler warns about correct code that you cannot
> make clearer (and adding a cast does not make the code any better at
> all), the compiler is bad. The warning is a spurious warning.

It can be expressed with the same effect:

if (n < 0)
return -1;

if (n < sizeof(struct pkthdr))
return SHORT_PACKET;

I agree that in this situations the compiler shouldn't warn and I
already mentioned this.

I never said that an experienced programmer cannot write perfectly
valid code which still causes tons of warnings. My point is only that
there with a few changes in the programming style and with a bit more
consideration while writing the code one can write equivalent code
(even on asm level) which does not cause warnings. Plus: I get
warnings for those cases which are really wrong and which you don't
see that easily without the warning. But of course this whole
discussion is void if there is no will to adapt to the new situation.
The new -Wall behaviour certainly clashes with most people's
programming style and if these people do not have any interest in
changing their style there will be no other solution for them other
than to remove this warning.

-- Uli
---------------. drepper@cygnus.com ,-. Rubensstrasse 5
Ulrich Drepper \ ,-------------------' \ 76149 Karlsruhe/Germany
Cygnus Solutions `--' drepper@gnu.ai.mit.edu `------------------------