I have been studying C lately and i have came across a source code of strlen which really confused me and i had to look it up in other places but couldnt really understand it yet.
strlen:
#include <stdio.h>
int strlen(const char *str)
{
const char* eos = str; // 1
while (*eos++); // 2
return (eos - str - 1); // 3
}
int main()
{
int len = strlen("Hello");
printf("Len: %d" , len);
return 0;
}
I couldnt understand why are we using the local variable eos and why are we using it in an empty while loop and then returning that last line from the strlen function ?
For starters the function return type should be size_t
.
size_t strlen(const char *str);
If two pointers point to elements of the same array then the difference between the pointer that points to the element with higher index and the pointer that points to the element with lower index yields the number of elements between the two indices.
For example if you have an array like
const char s[] = "12";
and two pointers
const char *p1 = &s[0];
const char *p2 = &s[1];
then the difference
p2 - p1
yields the value 1
.
This pointer within the original function
const char* eos = str;
will be moved across the passed string until the terminating zero character will be found.
while (*eos++);
This loop can be rewritten like
while ( *eos++ != '\0' );
The value of the postfix expression *esp++
is the value of the pointed character before incrementing the pointer.
So when the terminating zero is found the pointer eos
will point to the memory after the terminating zero character and the loop stops its iterations.
Thus now the pointer str
points to the beginning of the passed string and the pointer eos
points to the memory just after the terminating zero character '\0'
.
So the difference
(eos - str - 1)
gives the number of characters in the passed string that precede the terminating zero character '\0'
.