Zero initialization of POD types
struct Foo
{
char name[10];
int i;
double d;
};
I know that I can zero-initialize all elements of this type of POD with:
Foo foo = {0};
Can I simplify this even further:
Foo foo = {};
How are inline arrays? ( int arr[10] = {};
)
I don't ask when initializing with help {0}
if members other than the first will be initialized to zero. I know the answer to this question is yes. I ask if it is possible to syntactically skip the first one 0
.
Most of the tutorials I have found on this subject use {0}
, but not use {}
, for example this manual and it explains how it works because the aggregated initialization rules are recursive, which gives more confusion than explanation.
source to share
As written, this is aggregate initialization. The current rule is (§8.5.1 [dcl.init.aggr] / p7):
If the list has fewer initializer clauses than there are members in the aggregate, then each member is not explicitly initialized must be initialized from its own aligned or equal-initialized element, or, if there is no equalized or equal-initialized element, from an empty initializer list (8.5.4 ).
Relevant parts of §8.5.4 [dcl.init.list] / p3:
A list-initialization of an object or type reference is
T
defined as follows:
- If
T
is an aggregate, aggregate initialization (8.5.1) is performed.- Otherwise, if there are no elements in the initializer list, and
T
is a class type with a standard constructor, the object is the initialization value.- [irrelevant elements omitted]
- Otherwise, if there are no elements in the initializer list, the object is value-initialized.
In short, sub-aggregates are recursively aggregated-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-initializing means zero-initializing.
If it T
is a POD but is not an aggregate, then no aggregate initialization is applied, so you hit the second bullet point in §8.5.4 [dcl.init.list] / p3, which initializes the value of the entire object. POD classes must have a trivial default constructor that is not exposed to the user, so initializing values for them also means zero-initializing.
source to share