5
struct Foo
{
    char name[10];
    int  i;
    double d;
};

I know that I can zero-initialize all the members of such POD type with:

Foo foo = {0};

Can I further simplify this to:

Foo foo = {};

Like native arrays? (int arr[10] = {};)


I'm not asking when initializing with {0}, will the members except the first are zero-initialized. I know the answer to that question is yes. I'm asking if the first 0 can be omitted syntactically.

Most of the tutorials I found on this subject suggest using {0}, none using {}, e.g, this guide, and it's explained as This works because aggregate initialization rules are recursive;, which gives more confusion than explanation.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • @JoachimPileborg: That's terribly misleading. `int n;` is "like default constructing", but doesn't set to zero. It's rather that "`{}` is like value-initializing the data". – Kerrek SB Sep 12 '14 at 09:23

1 Answers1

5

As written, this is aggregate initialization. The applicable rule is (§8.5.1 [dcl.init.aggr]/p7):

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer, from an empty initializer list (8.5.4).

The relevant parts of §8.5.4 [dcl.init.list]/p3 is:

List-initialization of an object or reference of type T is defined as follows:

  • If T is an aggregate, aggregate initialization is performed (8.5.1).
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • [irrelevant items omitted]
  • Otherwise, if the initializer list has no elements, the object is value-initialized.

In short, sub-aggregates are recursively aggregate-initialized from an empty initializer list. Everything else is value-initialized. So the end result is everything being value-initialized, with everything being a POD, value-initialization means zero-initialization.


If T is POD but not an aggregate, then aggregate initialization doesn't apply, so you hit the second bullet point in §8.5.4 [dcl.init.list]/p3, which results in value-initialization of the entire object instead. POD classes must have a trivial (and so not-user-provided) default constructor, so value-initialization for them means zero-initialization as well.

T.C.
  • 133,968
  • 17
  • 288
  • 421