Questions about C strlen function

I tried to compare with strlen(string) with -1 but different methods gave different results:

char string[] = {"1234"};
int len = strlen(string);
int bool;
bool = -1 < strlen(string);
printf("%d",bool); //bool=0
bool = -1 < len;
printf("%d",bool); //bool=1

Assigning values to len and then comparing them gives the correct result, but I don’t understand why directly comparing with strlen doesn’t work.

>Solution :

Sign problem I guess, comparing to strlen must cast -1 to unsigned, so all bits set to 1, so whatever value is compared with, expression evaluates to 0.

While comparing with a typed variable, problem can’t occur since compiler doesn’t have to guess which operand has to be casted to other type.

What happens if you compile with -Wall -Wextra -Werror?
Error because of comparaison between invalid types?

Leave a Reply