calgorithmstrlen

C strlen() implementation in one line of code


Yesterday I was at interview and was asked to implement strlen() in C without using any standard functions, all by hand. As an absolute amateur, I implemented primitive version with while loop. Looking at this my interviewer said that it can be implemented at just one line of code. I wasn't be able to produce this code using that term at that moment. After interview I asked my colleagues, and the most experienced from them gave me this piece which really worked fine:

size_t str_len(const char *str)
{
    return (*str) ? str_len(++str) + 1 : 0;
}

So there is a question, is it possible without using recursion, and if yes, how?

Terms:

Please, take note that this is not the question of optimization or real using, just the possibility of make task done.


Solution

  • Similar to @DanielKamilKozar's answer, but with a for-loop, you can do this with no for-loop body, and len gets initialized properly in the function:

    void my_strlen(const char *str, size_t *len)
    {
        for (*len = 0; str[*len]; (*len)++);
    }