Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

strlen

Working on this little piece of code in VS2013, but for some reason it doesn't print.it seems that -1>strlen(str)

Anyone got an idea what i'm doing wrong

char *str="abcd";
if(-1<strlen(str))
printf("The size of the string is %d", strlen(str));    
return 0;
like image 508
Tj L Avatar asked May 18 '15 05:05

Tj L


People also ask

How does strlen work in C?

C strlen() The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type).

What is the difference between strlen () and sizeof ()?

strlen() is used to get the length of a string stored in an array. sizeof() is used to get the actual size of any type of data in bytes. Besides, sizeof() is a compile-time expression giving you the size of a type or a variable's type. It doesn't care about the value of the variable.

Does strlen exist in C?

(String Length) In the C Programming Language, the strlen function returns the length of the string pointed to by s. It does not include the null character in the length calculation.

What can I use instead of strlen in C?

strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).


1 Answers

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.

like image 86
Caleb Avatar answered Oct 07 '22 22:10

Caleb