In article <>
Sheldon Simms <> writes:
>In this case, you are comparing the value in [signed int] 'i' with
>a size_t. You shouldn't be doing this at all unless you *know* that the
>value in 'i' is unsigned.
Not necessarily: another option is "if a negative value of i is
supposed to be considered greater than the size_t value, which you
know is not `overflow-able'". That is, you know for certain that,
in:
i < u
the value in u is less than INT_MIN + UINT_MAX + 1, so that
all values of i in [INT_MIN..-1] result in values in the range
[INT_MIN + UINT_MAX + 1 .. UINT_MAX], which is less than u.
This test can be (re)written as:
i < 0 || i < (int)u
but this is probably even worse. Or you could write it as:
i >= 0 && (unsigned)i < u
but this is redundant.
(In the BSD kernel, we have a lot of code of the form:
if (i >= fdp->max || (fp = fdp->openfiles[i]) == NULL)
return (EBADF);
where fdp->max is known to be unsigned, so that signed-int interfaces
cannot use negative-valued file descriptors to escape system
security. Casting i gets rid of the warning; adding the redundant
"i < 0 ||" does not get rid of the warning and just makes the
compiler work hard to remove the redundant test. So, despite
my distaste for unnecessary casts, we either cast or live with
the warning.)
>If you know this, then you should make
>'i' unsigned (and change the name to something better like 'size').
That would be nice, but the interface is set in stone (or in POSIX
anyway, which is close enough to stone

).
>Your problem is really that SomeFunc() wants a pointer to (signed)
>int, when the value it is storing there is unsigned. The solution is
>to change SomeFunc(). If you can't do that, but you know *for sure*
>that SomeFunc() never writes a signed value into 'i', then cast the
>argument to SomeFunc().
Personally, I consider adding pointer casts -- i.e.,
unsigned int ui;
x = SomeFunc((int *)&ui);
... now use the "unsigned" value in ui ...
-- to be the worst of the various alternatives.
>If, however, you don't know for sure that SomeFunc() behaves properly
>(you don't have the souce code, for example), then you need to give
>SomeFunc() a pointer to int, and then check to make sure that it isn't
>negative before comparing it to sizeof(some_type).
Or, as I said above, guarantee that the test "i < 0 ||" is redundant
(as we do), and then either cast or live with the warning.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.