16

For example, what is the type of the string literal "Hello", const char[6] or const char* ?

Belloc
  • 6,318
  • 3
  • 22
  • 52

2 Answers2

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
  • Where is the temporary ? "hello" exists in static memory ! – Belloc Mar 19 '13 at 19:09
  • 1
    @user1042389 The **reference** to it is a temporary. –  Mar 19 '13 at 19:09
  • @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.