What is the type of a string literal in C++?

The code below compiles and the asserts do not fail:

#include <iostream>

int main()
{
    auto a = "str";
    const auto& ar = "str";
    const char* b = "str";
    auto const &c = a;
    auto* d = &a;
    const auto e = 2;

    static_assert(std::is_same_v<const char(&)[4], decltype("str")>);
    static_assert(std::is_same_v<const char*, decltype(a)>);
    static_assert(std::is_same_v<const char(&)[4], decltype(ar)>);
    static_assert(std::is_same_v<const char* const&, decltype(c)>);
    static_assert(std::is_same_v<const char**, decltype(d)>);
    static_assert(std::is_same_v<const int, decltype(e)>);

    std::cout << "a: " << typeid(a).name() << std::endl;
    std::cout << "ar: " << typeid(ar).name() << std::endl;
    std::cout << "b: " << typeid(b).name() << std::endl;
    
    return 0;
}

And a and b have identical typeids.

1 Response to What is the type of a string literal in C++?

Leave a Reply

Your email address will not be published. Required fields are marked *