why is -1>strlen(t) true in C? [duplicate]

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.

Leave a Comment