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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With