Search code examples
c++c-stringsstring-lengthstring-literalscompile-time-constant

Is strlen Optimized out for String Literals?


So say that I have this:

const auto foo = "lorem ipsum"

If I use strlen(foo) in my code, is the 11 found at run time or is that injected at compile time?


Solution

  • The standard doesn't allow implementations to add constexpr, except where it is explicitly required:

    [constexpr.functions]
    This document explicitly requires that certain standard library functions are constexpr ([dcl.constexpr]). An implementation shall not declare any standard library function signature as constexpr except for those where it is explicitly required.

    So strlen is out of bounds.

    However, to support constexpr constructors of string_view, the C++17 standard requires that certain members of char_traits, like char_traits::length, are constexpr anyway.

    And this month we have had new compiler releases of gcc 8.1 and MSVC 15.7 so that the latest versions of the major compilers now all implement char_traits::length as constexpr.