Shruts_me - 1 year ago 101
C Question

# What will be the value of strlen(str)- 1 in a 'for' loop condition when str is empty?

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?

This statement

``````printf(" %d,  %ul,  %u, %d,  %ul, %u", strlen(str),strlen(str),strlen(str),strlen(str)-1,strlen(str)-1,strlen(str)-1);
``````

shows that when `strlen( str ) - 1` is outputed like unsigned integer for example using format specifier `%ul` its value is `4294967295l`

In the condition of the loop

``````for (int i=0;i<strlen(str)-1;i++)
``````

the compiler has to determine the common type of the left and right operands that to determine the type of the result of the condition

``````i<strlen(str)-1
``````

The right operand `strlen(str)-1` has type `size_t` (the return type of function `strlen` is `size_t`). It is unsigned integer type usually that corresponds to `unsigned long`. It can not have negative values. Any value that stored in an object of this type is interpretated as a non-negative value and as the output shows the value of `strlen(str)-1` is equal to `4294967295l`. (The actual value you could get if you used type specifier `%zu` because it may not be excluded that `size_t` can correspond even to unsigned long long)

The right operand has type `int`. Its rank is at least not greater than the rank of size_type. So the both operands are converted to type `size_t` and have non-negative values.

This procedure of determining of the common type is called the usual arithmetic conversions. It is obvious that `4294967295l` is greater than 0. Thus the loop will iterate `4294967295l` times if it does not have a break statement.

You could get the expected result if you rewrite the condition in the loop the following way

``````for ( int i = 0; i < ( int )strlen( str ) - 1; i++ )
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download