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?
An unsigned integer can never hold a negative value. If the value of i is negative, then it will be converted to some positive value when you assign it to j . If you want to know whether the value of i is negative, you should test i , not j .
An unsigned is an integer that can never be negative. If you take an unsigned 0 and subtract 1 from it, the result wraps around, leaving a very large number (2^32-1 with the typical 32-bit integer size).
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.
Zero (0) is also unsigned number. This representation has only one zero (0), which is always positive. Every number in unsigned number representation has only one unique binary equivalent form, so this is unambiguous representation technique.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With