Code Golf: strlen() implementation

Can you do a strlen implementation in just one line? Being that line under 80 characters (no cheating), and without the use of if-else statements, and/or while loops?

Yes, you can.

size_t strlen(const char *s) 
{
return((*s)?(strlen(++s)+1):(size_t)*s);
}

Don’t believe me? Try to compile it.

How does it work?

Recursion :)

Image for post
Image for post
First, let’s create our string, a simple “Hello world!”.
Image for post
Image for post
Next, by recursion, we will iterate the whole array (string), until we find the null character.
Now, we have our pointer (used as a counter) value saved in memory.
Image for post
Image for post
And viola! We exit from the recursion, and return the length of the string.

Procrastinating much?

Maybe…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store