Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen() compile time optimization

Few days ago I discovered that you can find compile-time strlen using something like this:

template<size_t N>
constexpr size_t strlen_(const char (&data)[N]) noexcept{
    return N - 1;
}

If it's compiled, then all is good. You can add overload such this:

size_t strlen_(const char *s) noexcept{
    return strlen(s);
}

Then it will always compiles.

My question is - does C++ <cstring> uses something like this and if it does not - why?

like image 295
Nick Avatar asked Apr 03 '16 19:04

Nick


2 Answers

No, it doesn't. Because it gives the wrong answer.

char x[10] = "abc";
int correct_length   = std::strlen(x);  // 3
int incorrect_length = strlen_(x);      // 9

Also, with your 2 overloads, the template will never be called. The non-template one accepting a const char* will always be preferred.

This doesn't mean that strlen can't be calculated at compile time with some compiler magic. But it can't be done this way, using the language proper.

like image 77
Benjamin Lindley Avatar answered Oct 29 '22 14:10

Benjamin Lindley


Your strlen_returns the size of arraydata, not the size of a null-terminated string. A correct implementation would be:

constexpr size_t ct_strlen( const char* s ) noexcept
{
  return *s ? 1 + ct_strlen(s + 1) : 0;
}
like image 41
zdf Avatar answered Oct 29 '22 13:10

zdf