C implementation of strlen () in one line

Question:

Recently I attended an interview, one of the tasks was to implement the strlen() functionality without using third-party functions, that is, by hand. As a complete dilettante in C, I have drawn a simple loop. It was pointed out to me that this implementation is uneconomical, and also that it can be written without unnecessary variables and in one line. Of course, not in the sense of sticking everything in one line, but a different algorithm. It was not about performance or optimization from a practical point of view, and as I understand it, the question was purely academic. This piqued my interest, since I could not do it during the interview. Communicating with a more competent colleague, I received from him the implementation:

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

I probably would not have thought of this myself, but now a colleague has a question – is there a one-line option without recursion?

PS: I also started a topic on SO on the topic of the same name. I hope it will be interesting to those who participated in the discussion.

Answer:

It is impossible in Xi. Everything that can be written in one line and without calling other functions is executed in O (1) time, and we need to write an algorithm that works at least O (N) (N is the length of the line).

Scroll to Top