Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 598
Shruts_me Avatar asked Jul 11 '15 20:07

Shruts_me


People also ask

What is strlen str 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.

What does strlen 0 is equal to?

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.

What is strlen str?

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'.

Does strlen return an int?

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).


1 Answers

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.

like image 180
P.P Avatar answered Nov 10 '22 01:11

P.P