lkml.org 
[lkml]   [1997]   [Sep]   [24]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
From
SubjectRe: Style question: comparison between signed and unsigned?
Date
In article <yv2wwk7etir.fsf@i44d2.i-have-a-misconfigured-system-so-shoot-me>,
Ulrich Drepper <drepper@ipd.info.uni-karlsruhe.de> wrote:
>
>And (I don't know who mentioned this)
>
> int n = read (...);
>
>is of course plainly wrong. `read` returns ssize_t.

No Ulrich, YOU are wrong. read() may return ssize_t, but that has
absolutely no bearing on the problem.

There is nothing at all wrong with

int n = read(...);

within the context posted. The C language has well-defined integer
conversions, and let's look at the code a bit from the programmers point
of view:

- we know we have to use a signed value to be able to handle the -1
case.

- we know we have to have to have enough bits for the return value, but
as we're reading into some random buffer that we have defined, we
_know_ int is going to be enough.

- 'int' is the normal type for some random integer. It's essentially
the default type.

In short, 'int' is sufficient, simple, and correct. Calling the above
code "wrong" is a lot more wrong than the code itself. It's the
stickler approach - blaming perfectly good code on some technical detail
that doesn't have any real merit.

And that's part of the whole problem: the compiler warning about
signedness is exactly as valid (or invalid, in my opinion) as the
compiler warning about the size of integer arguments.

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?

Sure, let's just add lots of casts to make the compiler think we know
what we're doing. THAT makes sense. Not.

For the same reason it is completely correct to do

int n = read(...);

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.

Linus

\
 
 \ /
  Last update: 2005-03-22 13:40    [W:0.051 / U:0.512 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site