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.