[Solved] Type of strings


The type of foo is char[4], i.e. a character array containing 4 chars (including the trailing null character '\0'.)

String literals can be used to initialize character arrays. If an array is initialized like char str[] = "foo";, str will contain a copy of the string "foo".

The type of bar is char *, qux is char const *, just as you declared.

"bar" is string literal with type const char[4], i.e. an array containing 4 const chars (also including the trailing null character '\0'.)

The null character ('\0', L'\0', char16_t(), etc) is always appended
to the string literal: thus, a string literal "Hello" is a const char[6]
holding the characters 'H', 'e', 'l', 'l', 'o', and '\0'.

Here’s a helper class which could give the exact type at compile-time (the idea is borrowed from Effective.Modern.C++ written by Scott Meyers).

template <typename>
struct TD;

then use it like

TD<decltype(foo)> td1;
TD<decltype("bar")> td2;
TD<decltype(bar)> td3;
TD<decltype(qux)> td4;

e.g. from clang you’ll get error message containing type information like:

prog.cc:12:23: error: implicit instantiation of undefined template 'TD<char [4]>'
    TD<decltype(foo)> td1;
                      ^
prog.cc:13:25: error: implicit instantiation of undefined template 'TD<char const (&)[4]>'
    TD<decltype("bar")> td2;
                        ^
prog.cc:14:23: error: implicit instantiation of undefined template 'TD<char *>'
    TD<decltype(bar)> td3;
                      ^
prog.cc:15:23: error: implicit instantiation of undefined template 'TD<const char *>'
    TD<decltype(qux)> td4;
                      ^    

BTW: Because string literals are treated as lvalues, and decltype yields type of T& for lvalues, so the above message from clang gives the type of "bar" as an lvalue-reference to array, i.e. char const (&)[4].

8

solved Type of strings