Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++20

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?

like image 730
Eric Avatar asked Dec 14 '20 14:12

Eric


People also ask

Does C initialize structs to 0?

You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.

What is designated initialization in C?

Designated initializers, a C99 feature, are supported for aggregate types, including arrays, structures, and unions. A designated initializer, or designator, points out a particular element to be initialized.

Are structs default initialized?

When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.

What is brace initialization C++?

Declaring a variable with braces in C++ Initialization occurs when you provide a variable with a value. In C++, there are several methods used to declare and initialize a variable. The most basic way to initialize a variable is to provide it with a value at the time of its declaration.


1 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.

like image 90
Barry Avatar answered Oct 23 '22 01:10

Barry