Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading