I am quite confused with the behavior of strlen
,the for loop below never ends (without adding the break
) when try it, while the i < -2 should return False in the first step.
Is it related to my compiler? What did I misunderstand?
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "longstring";
char b[] = "shortstr";
printf("%d\n", strlen(b) - strlen(a)); // print -2
for (int i = 0; i < strlen(b) - strlen(a); i )
{
printf("why print this, %d %d\n", i, strlen(b) - strlen(a));
break;
}
return 0;
}
Output
-2
why print this, 0 -2
CodePudding user response:
The conversion specifier in this call of printf
printf("%d\n", strlen(b) - strlen(a)); // print -2
is incorrect. The function strlen
returns a value of the unsigned integer type size_t
. So this expression strlen(b) - strlen(a)
also has the type size_t
. So you need to write either
printf("%d\n", ( int ) strlen(b) - ( int )strlen(a) ); // print -2
or
printf("%zu\n", strlen(b) - strlen(a)); // print a big positive value.
In the condition of the for loop
for (int i = 0; i < strlen(b) - strlen(a); i )
the expression strlen(b) - strken(a)
as it has been mentioned above has the unsigned integer type size_t
. So its value can not be a negative and represents a big positive value.
Again instead you need to write
for (int i = 0; i < ( int )strlen(b) - ( int )strlen(a); i )
Or you could write
for ( size_t i = 0; i strlen( a ) < strlen(b); i )
CodePudding user response:
strlen(b) - strlen(a);
is a negative number
and i
is 0 or ve
Therefore the loop
for (int i = 0; i < strlen(b) - strlen(a); i )
Will never end as i
( ve) will never be -ve