For example, what is the type of the string literal "Hello", const char[6]
or const char*
?
Asked
Active
Viewed 1.5k times
16

Belloc
- 6,318
- 3
- 22
- 52
-
13`const char[6]`. – juanchopanza Mar 19 '13 at 18:56
-
1what do you mean by saying "type"? – nabroyan Mar 19 '13 at 18:56
-
1@nabroyan In C++, every value has a type. OP wants to know the type of a string literal. – Mar 19 '13 at 19:00
-
1@H2CO3 I know that, but he answered his question right in his answer, so I taught that he means something else – nabroyan Mar 19 '13 at 19:03
-
@nabroyan what makes you think OP answered his own question? – Kröw Jul 04 '23 at 05:13
2 Answers
20
The type of the string literal "Hello"
is "array of 6 const
char
".
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n
const char
”, where n is the size of the string [...]
It can, however, be converted to a const char*
by array-to-pointer conversion. Array-to-pointer conversion results in a pointer to the first element of the array.

Joseph Mansfield
- 108,238
- 20
- 242
- 324
-
This probably explains why this code shows a warning `C4172 returning address of local variable or temporary`for this function `const char* const& f() { return "hello"; }` in VS2010. Do you agree with this ? – Belloc Mar 19 '13 at 19:02
-
1@user1042389 The pointer resulting from the array-to-pointer conversion is a temporary object. You are returning a reference to that object, so that reference is left dangling. – Joseph Mansfield Mar 19 '13 at 19:05
-
-
1
-
@H2CO3 `const int& f() { static int i = 0; return i; }`compiles without a warning. – Belloc Mar 19 '13 at 19:12
-
1@user1042389 The *array* exists in static memory. The pointer that we get from array-to-pointer conversion is temporary. Just like if you have an `int x;` and do `(float)x` - the casted `float` is temporary. – Joseph Mansfield Mar 19 '13 at 19:17
-
@user1042389 for your example to be similar try const int& f() { static long i = 0; return static_cast
( i ); } – Slava Mar 19 '13 at 19:17 -
Why the warning then for this snippet `const char* const& f() { return static_cast
("hello"); }`? – Belloc Mar 19 '13 at 19:24 -
@user1042389 Because the pointer you're returning is still a temporary object. – Joseph Mansfield Mar 19 '13 at 19:26
5
The Standard defines it as an "array of n const char
", so it's const char[n]
(n is the size of the string, including the terminating NUL byte).
Section 7, § 2.14.15:
A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration.