auto with string literals

Viewed 4805
#include <iostream>
#include <typeinfo>

int main()
{
    const char a[] = "hello world";
    const char * p = "hello world";
    auto x = "hello world";

    if (typeid(x) == typeid(a))
        std::cout << "It's an array!\n";

    else if (typeid(x) == typeid(p))
        std::cout << "It's a pointer!\n";   // this is printed

    else
        std::cout << "It's Superman!\n";
}

Why is x deduced to be a pointer when string literals are actually arrays?

A narrow string literal has type "array of n const char" [2.14.5 String Literals [lex.string] §8]

3 Answers

If you want x to be deduced as array, you can use

decltype(auto) x = "hello world";
Related