Re: Style question: comparison between signed and unsigned?

Linus Torvalds (torvalds@transmeta.com)
22 Sep 1997 20:24:12 GMT


In article <Pine.LNX.3.95.970922182742.3769W-100000@pc12.sr.bham.ac.uk>,
Mark Cooke <mpc@star.sr.bham.ac.uk> wrote:
>On Mon, 22 Sep 1997, Thomas Koenig wrote:
>
>> What do other people feel? Should signed/unsigned conversions be
>> avoided in new code? Should these be eliminated in 2.2? Will patches
>> towards that goal be accepted if all they do is clean up error
>> messages?
>
>Signed/unsigned comparisions should (nearly) _always_ be avoided. It's a
>symptom of inconsistancy/sloppy typedefs in the code. If it doesn't bite
>you today, it might bite you tomorrow on a different architecture.

That's not always true.

The problem is not so much your own types - the problem can often be the
types of "C things", mainly 'sizeof(x)'. For example, the following
code is perfectly valid:

struct bufhdr *p;
char buffer[MAXBUFSIZ];
int i = read(socket, buffer, sizeof(buffer));

/* error? */
if (i == -1)
return i;

/* Did we get a valid packet? */
if (i < sizeof(struct bufhdr))
return SHORT_PACKET;

p = (struct bufhdr *) buffer;
switch (p->type) {
...

and the compiler should not warn about the fact that we compare an "int"
(signed) with a "sizeof(x)" (unsigned).

Likewise, if you say "just add a cast", that's just WRONG! Good C
programming rules are that you should _never_ add a cast, at least in my
opinion. There are cases where casts have their place, but the above is
not one of them. The above is perfectly good code, and adding a cast
makes it not more readable or better, but just _less_ readable and
worse.

Linus