why is -1>strlen(t) true in C? [duplicate]
Solution 1:
Anyone got an idea what i'm doing wrong
strlen()
returns a size_t
, which is an unsigned integer type. -1
interpreted as an unsigned integer is a large value, so it ends up being greater than the length of your string. You can use the -Wsign-compare
flag in gcc
and some other compilers to warn you when you try to compare signed and unsigned values.
Also, it doesn't make much sense to compare the length of a string to -1
. A length can never be negative; it's always going to be 0
or greater. So you'll probably want to rewrite your code to test against 0
, or otherwise properly implement whatever condition you're trying to test for.
if(-1<strlen(str)) printf("The size of the string is %d", strlen(str));
In this code, you might reasonably expect the test to always succeed and the printf()
to execute, since the length is always 0
or more. But you're finding that the test actually fails and the printf()
never happens because -1
is promoted to an unsigned so that it can be compared to a size_t
. The easy solution is to remove the condition altogether: you know the test will always succeed, so there's no need for it. Just remove the if
*:
printf("The size of the string is %zu", strlen(str));
*Also, change the print format specifier from %d
to %zu
since, as Matt McNabb pointed out in a comment, you're trying to print a size_t
.
Solution 2:
strlen(str)
returns an unsigned integer. When comparing signed integer with unsigned integer, the compiler converts the signed value to unsigned. When converted to unsigned, -1
becomes 2^32 - 1
(assuming that strlen returns a 32 bit integer), which is greater than the length of the string you are comparing with.
Solution 3:
strlen
returns a value of type size_t
. This is an unsigned integral type.
The rule in C for when comparing a signed value with a value of the corresponding unsigned type, is that the signed value is converted to the unsigned value.
If the values are of different sized types, for example if your system has 4-byte int
and 8-byte size_t
, then the rule is that the value of smaller type is converted to the value of the larger type.
Either way this means that -1
is converted to size_t
, resulting in SIZE_MAX
which is a large positive value. (unsigned types cannot hold negative values).
This large positive value is greater than the length of your string, so the less-than comparison returns false.