I am analyzing a scenario:
char str[] = ""; // Understand
If I understand strlen(str)
, it comes out to be 0. This is OK.
printf(" %d, %ul, %u, %d, %ul, %u",
strlen(str),
strlen(str),
strlen(str),
strlen(str) - 1,
strlen(str) - 1,
strlen(str) - 1);
Output is:
0, 0l, 0, -1, 4294967295l, 4294967295
I understand these as well.
for (int i = 0; i < strlen(str) - 1; i++)
{
}
Here I don't understand what the value of strlen(str) - 1
would be in the for
loop condition.
strlen(str) - 1
is giving the value 4294967295 in the for loop.
Why is that? Why not -1?
strlen returns size_t which is an unsigned integer. So strlen(str)-1 would produce SIZE_MAX (the maximum value size_t can hold) if strlen(str) is 0 . You should be using %zu to print size_t values. Follow this answer to receive notifications.
strlen returns the length of bytes of a string. strlen($str)==0 is a comparison of the byte-length being 0 (loose comparison). That comparison will result to true in case the string is empty - as would the expression of empty($str) do in case of an empty (zero-length) string, too.
The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.
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).
strlen
returns size_t
which is an unsigned integer. So strlen(str)-1
would produce SIZE_MAX
(the maximum value size_t
can hold) if strlen(str)
is 0
.
You should be using %zu
to print size_t
values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With