Home >Backend Development >C++ >When to Omit Outer Braces in C Initializer Lists?

When to Omit Outer Braces in C Initializer Lists?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 09:27:24620browse

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

In your example, std::array a1 requires explicit braces because std::array is an aggregate and a POD type. The first member of the aggregate is an array of size N, where N is passed as a template argument. To initialize this member directly, you need to use extra braces for the inner array. In your incorrect code example:

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:

  • If the initializer list begins with a left brace, then all members of the subaggregate are initialized, and extra braces are not needed.
  • If the initializer list doesn't begin with a left brace, only enough initializer-clauses are taken from the list to fill the current subaggregate, and any remaining clauses initialize the next member of the aggregate.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn