Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding strlen function in C

Tags:

c

I am learning C. And, I see this function find length of a string.

size_t strlen(const char *str) 
{ 
 size_t len = 0U; 
 while(*(str++)) ++len; return len; 
}

Now, when does the loop exit? I am confused, since str++, always increases the pointer.

like image 241
jess Avatar asked Sep 20 '10 10:09

jess


2 Answers

while(*(str++)) ++len;

is same as:

while(*str) {
 ++len;
 ++str;
}

is same as:

while(*str != '\0') {
 ++len;
 ++str;
}

So now you see when str points to the null char at the end of the string, the test condition fails and you stop looping.

like image 176
codaddict Avatar answered Nov 15 '22 14:11

codaddict


  1. C strings are terminated by the NUL character which has the value of 0
  2. 0 is false in C and anything else is true.

So we keep incrementing the pointer into the string and the length until we find a NUL and then return.

like image 44
doron Avatar answered Nov 15 '22 12:11

doron