Home >Backend Development >C++ >When Are Outer Braces Required in C Initializer Lists for `std::array` and Similar Aggregates?
When Outer Braces Cannot Be Omitted in an Initializer List
In C , outer braces are required for initializer lists when dealing with certain types of aggregate structures, specifically those that are Plain Old Datatypes (PODs) or lack user-defined constructors. Unlike most containers in the standard library, std::array falls into this category.
std::array Initialization with Braces
Consider the following example:
std::array<A, 2> a1 = { {0, 0.1}, {2, 3.4} };
where A is a struct with two data members. The extra set of braces enclosing {0, 0.1}, {2, 3.4} is essential because it initializes the internal array of std::array. Without them, the compiler will report "too many initializers" error.
Direct Array Initialization
This behavior is analogous to direct array initialization:
Aarray a1 = { {0, 0.1}, {2, 3.4} };
Here, the internal array data of the Aarray struct is being initialized directly. Without the outer braces, the compiler would encounter the same error as with std::array.
Comparison with Scalar Types
When initializing arrays of scalar types like double, outer braces are optional because scalar types are not aggregates. For instance:
std::array<double, 2> a2 = {0.1, 2.3};
In this case, extra braces are not required since the data member of the array is already directly initialized by the initializer list {0.1, 2.3}.
The above is the detailed content of When Are Outer Braces Required in C Initializer Lists for `std::array` and Similar Aggregates?. For more information, please follow other related articles on the PHP Chinese website!