Reputation: 185
Playing with some sources found code like this:
void foo(unsigned int i)
{
if(i<0)
printf("Less then zero\n");
else
printf("greater or equ\n");
}
int main()
{
int bar = -2;
foo(bar);
return 0;
}
I think there is no sense, but may be there some cases(security?) that makes this check sensable?
Upvotes: 8
Views: 13521
Reputation: 1413
An unsigned int cannot be less than 0 by definition. So, to more directly answer your question, you're right in thinking that this makes no sense. It is not a meaningful security item either unless you encounter something like a loop that accidently decrements a signed int past 0 and then casts it as an unsigned int for use as an index into an array and therefore indexes memory outside of the array.
Upvotes: 13
Reputation: 2290
i
will always be >=0
because it is declared as unsigned
and thus interpreted as an unsigned integer.
So your first test will always be false.
Your call foo(bar)
actually converts an int
into an unsigned int
. This may be what confuses you. And "conversion" does not actually change the bytes/bits value of your integer, it is just a matter of formal typing and interpretation.
See this answer for examples of signed/unsigned conversions.
Here is a simple example (the exact output depends on the number of bytes of an unsigned int
on your system, for me it is 4 bytes).
Code:
printf("%u\n", (unsigned int) -2);
Output:
4294967294
Upvotes: 2