4

According to question What does string array[] = ""; mean and why does it work? I want to ask what difference between s1 and s2 in the code below:

int main() {
    const char* s1 = { "Hello" }; // strange but work as followed
    const char* s2 = "Hello"; // ordinary case 
    return 0;
}

Why extra curly braces are permitted? Any reference to C++ standard will be useful.

Community
  • 1
  • 1
αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71

2 Answers2

12

In C++98 (and C++03) this is pretty simple; in clause 8.5:

14 - If T is a scalar type, then a declaration of the form T x = { a }; is equivalent to T x = a;

In C++11 this is covered by list-initialization (8.5.4p3):

[...] if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element [...]

I think this is the same question as Initializing scalars with braces.

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
-1

The simple answer is: because the standard says so. §8.5.2/1:

A char array (whether plain char, signed char, or unsigned char), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow character literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array.

(That's C++11, but earlier versions said the same thing, minus the references to the new types.)

The reason this is allowed is because C allowed it. As to why C allowed it, I have no idea.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • @JoachimPileborg that's irrelevant (and somewhat contentious); the standard is referring to the object being initialized, which is not a string literal. – ecatmur Jan 31 '14 at 14:21
  • @JoachimPileborg The type _getting initialized_ here is a pointer ("scalar type"), not an array ("aggregate type"). So the cited text is irrelevant to the question. Another answer is citing the relevant part of the standard. – Lundin Jan 31 '14 at 14:23
  • `s1` is a scalar, not an array. 8.5.2/1 doesn't apply here. – John Dibling Jan 31 '14 at 14:27