Messages in this thread | | | From | (Linus Torvalds) | Subject | Re: Style question: comparison between signed and unsigned? | Date | 24 Sep 1997 02:16:51 GMT |
| |
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
| |