Home >Backend Development >C++ >When to Omit Outer Braces in C Initializer Lists?
When Omitting Outer Braces in Initializer Lists
In C , when initializing an aggregate type such as a struct or array, you may face the question of whether or not to use outer braces in the initializer list. In the case of aggregate types that are POD (Plain Old Data) and have no user-defined constructors, such as std::array, outer braces are required. However, for aggregates that do not have this restriction, like built-in types, these braces can be omitted.
Explicit Braces for POD Aggregates
std::array<A, 2> a1 = { {0, 0.1}, {2, 3.4} };
the compiler reports "too many initializers" because the inner braces are missing. The correct initialization with braces is:
std::array<A, 2> a1 = { {{ {0, 0.1}, {2, 3.4} }} };
Eliding Braces for Non-POD Aggregates
In contrast to POD aggregates, non-POD aggregates like built-in types do not require explicit outer braces in initializer lists. For instance, your example:
std::array<double, 2> a2 = {0.1, 2.3};
doesn't include braces for the inner array. This is because double is not an aggregate, and the initializer list directly initializes the constituent double elements.
Additional Insights from the Standard
The C standard provides guidance on when outer braces can be omitted in initializer lists:
This allows for initialization with both braces and without braces, as long as the number of initializer-clauses matches the number of members to be initialized.
The above is the detailed content of When to Omit Outer Braces in C Initializer Lists?. For more information, please follow other related articles on the PHP Chinese website!