Ambiguous Initializer Syntax for Aggregates Containing Arrays
In C , when initializing aggregates containing arrays, omitting curly braces can lead to confusion and errors. This is evident in the following examples:
// Error: Too many initializers std::array<A, 2> a1 = { {0, 0.1}, {2, 3.4} }; // Valid std::array<double, 2> a2 = {0.1, 2.3};
Braces Required for std::array of Structures
The first example throws an error because std::array is an aggregate and lacks a user-defined constructor. Initialization of its internal array requires explicit braces, as seen in the corrected version:
std::array<A, 2> a1 = { {{0, 0.1}, {2, 3.4}} };
Braces Not Required for std::array of PODs
In contrast, std::array
Consistency for Aggregates
The principle of requiring braces for aggregate members applies to other types of aggregates as well:
// Valid B meow1 = {1, 2}; B bark1 = {{1, 2}}; C meow2 = {1, 2}; C bark2 = {{1, 2}};
Ambiguity in D
However, the following example leads to an error:
// Error: Too many initializers D meow3 = {{1, 2}, {3, 4}}; D bark3 = {{{1, 2}, {3, 4}}};
In D, the initializer for foo is itself an array. The braces in meow3 are ambiguous because they could refer to either the initialization of foo or its internal array. To resolve the ambiguity, explicit braces are required, as in bark3.
Mechanism for Initializing Aggregates
When braces are omitted in aggregate initialization, several rules apply:
Additional Examples
The above is the detailed content of When to Use Braces in C Aggregate Initialization with Arrays?. For more information, please follow other related articles on the PHP Chinese website!