Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra curly braces while initializing a string

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.

like image 957
αλεχολυτ Avatar asked Dec 25 '22 14:12

αλεχολυτ


1 Answers

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.

like image 161
ecatmur Avatar answered Jan 05 '23 02:01

ecatmur