Are left out fields by C++ 20 designated initialization guaranteed to be zero initialized?

Viewed 146

When using C++ 20 designated intializers it is not required to specify a value for every field:

struct Foo
{
    int i;
    void* p;
};

can be initialized like this:

Foo bar = {
    .i = 22
};

Are the left out fields zero-intialized? So in this example is p guaranteed to be set to nullptr?

2 Answers

Are the left out fields zero-intialized?

In this case, yes. The rule is (from [dcl.init]/5):

For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:

  • If the element has a default member initializer ([class.mem]), the element is initialized from that initializer.
  • Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]).
  • Otherwise, the program is ill-formed.

In this case p is not explicitly initialized. It has no default member initializer, so we fall to the second bullet. It is not a reference, so it is copy-initialized from {}. For a void*, that's zero-initialization.

Related