#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]
A string literal is a sequence of zero or more characters enclosed within single quotation marks. The following are examples of string literals: 'Hello, world!' '10-NOV-91' 'He said, "Take it or leave it."'
The strcat() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string. No length checking is performed. You should not use a literal string for a string1 value, although string2 may be a literal string.
A raw string literal is a null-terminated array—of any character type—that contains any graphic character, including the double quotation mark ( " ), backslash ( \ ), or newline character. Raw string literals are often used in regular expressions that use character classes, and in HTML strings and XML strings.
String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".
The feature auto
is based on template argument deduction and template argument deduction behaves the same, specifically according to §14.8.2.1/2 (C++11 standard):
If you want the type of the expression x
to be an array type, just add &
after auto
:
auto& x = "Hello world!";
Then, the auto
placeholder will be deduced to be const char[13]
. This is also similar to function templates taking a reference as parameter. Just to avoid any confusion: The declared type of x will be reference-to-array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With