What is the datatype of string literal in C++?

I'm confused about the datatype of a string literal. Is it a const char * or a const char?


Solution 1:

It is a const char[N] (which is the same thing as char const[N]), where N is the length of the string plus one for the terminating NUL (or just the length of the string if you define "length of a string" as already including the NUL).

This is why you can do sizeof("hello") - 1 to get the number of characters in the string (including any embedded NULs); if it was a pointer, it wouldn't work because it would always be the size of pointer on your system (minus one).

Solution 2:

"Hello world" is const char[12] (eleven characters plus '\0' terminator).

L"Hello world" is const wchar_t[12].

And since C++14, "Hello world"s is std::string.

Also note the u8"", u"" and U"" string literal notations added by C++11, which specify UTF-8, UTF-16 and UTF-32 encoding, respectively. The encoding of non-qualified string literals (i.e. "" and L"") is (and always was) implementation-defined.