Auto with String Literals

#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 an array!\n"; else if (typeid(x) == typeid(p)) std::cout << "It a pointer!\n"; // this is printed else std::cout << "It Superman!\n"; } 

Why is x displayed as a pointer when string literals are actually arrays?

A narrow string literal is of the type "array of n const char " [2.14.5 String literals [lex.string] §8]

+15
c ++ c ++ 11 type-inference string-literals auto
Aug 18 '12 at 7:25
source share
2 answers

The auto function is based on the output of the template argument, and the output of the template argument behaves similarly, in particular, according to §14.8.2.1 / 2 (C ++ 11 standard):

  • If P is not a reference type
    • If A is an array type, the pointer type created by the conversion from array to pointer is used instead of A to deduce the type

If you want the type of expression x be an array type, just add & after auto :

 auto& x = "Hello world!"; 

Then the auto placeholder will be displayed as const char[13] . It also looks like function templates that take a link as a parameter. Just to avoid confusion: the declared type x will be an array reference.

+20
Aug 18 2018-12-12T00:
source share

Why is x output as a pointer when string literals are actually arrays?

Due to the conversion of the array to a pointer.

If x should be output as an array, only if the following is allowed:

 const char m[] = "ABC"; const char n[sizeof(m)] = m; //error 

In C ++, an attribute cannot be initialized with another array (e.g. above). In such cases, the original array breaks up into a pointer type, and you can do this instead:

 const char* n = m; //ok 

The rules for type inference with auto similar to the rules for type inference in a function template:

 template<typename T> void f(T n); f(m); //T is deduced as const char* f("ABC"); //T is deduced as const char* auto n = m; //n type is inferred as const char* auto n = "ABC"; //n type is inferred as const char* 

§7.1.6.4 / 6 refers to the auto qualifier:

The type deduced for the variable d, then deduced A is determined using the rules for deriving the template argument from the function call (14.8.2.1) ...

+4
Aug 18 2018-12-18T00:
source share



All Articles