C strlen() implementation in one line of code

Alex picture Alex · Mar 20, 2014 · Viewed 12.8k times · Source

Yesterday I was at interview and was asked to implement strlen() in C without using any standard functions, all by hands. 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:

  • without any assembler
  • without any C functions existed in libraries
  • without just spelling few strings of code in one

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

Answer

Digital Trauma picture Digital Trauma · Mar 20, 2014

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)++);
}