Search code examples
c++c++11charstring-literalsdecltype

String literal type is not as expected


Consider the following program:

#include <iostream>
#include <type_traits>

int main(int argc, char* argv[])
{
    std::cout << std::is_same<decltype("hello"), char*>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), const char*>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), char[5]>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), const char[5]>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), char[6]>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), const char[6]>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), char[]>::value << std::endl;
    std::cout << std::is_same<decltype("hello"), const char[]>::value << std::endl;
    return 0;
}

It returns only zeroes, while I would have expected "hello" to be a const char[6]. What is the type of "hello"?


Solution

  • Edit: I was too quick and didn't notice the const char[6]. Since none of your checks involve &:

    Quoting 8.4.1 Literals:

    A literal is a primary expression. Its type depends on its form. A string literal is an lvalue; all other literals are prvalues.

    Hence, the type is const char (&)[6].