Search code examples
c++c++14constexprc-stringsstring-literals

Returning a C string in a constexpr function: why no warning from the compiler?


Consider the following code:

constexpr auto f()
{
    auto str = "Hello World!";
    return str;
}

int main(int argc, char* argv[])
{
    static constexpr auto str = f();
    std::cout << str << std::endl;
    return 0;
}

Is that normal that my compiler does not display any warning? Is it defined behavior? Do I have the guarantee that the program will display "Hello World!"? I would expect the "Hello World!" not to live beyond the scope of the function...


Solution

  • In C++ string literals have static storage duration and live as long as the program runs. So, a pointer to a string literal returned from f is always valid. No allocation or deallocation is involved.

    Note that string literals have type const char[N], which in your case decays to const char * due to auto type deduction. If your intent was to use std::string, you can directly construct it

    auto str = std::string("Hello World!");
    

    or use operator""s:

    using std::string_literals;
    auto str = "Hello World!"s;
    

    However, since std::string is not a literal type, this values cannot be constexpr anymore.