I'm debugging some code that essentially is identical to this:
struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };
When I make an instance of Bar
, it seems like both a
and b
are initialized to zero. Is this guaranteed? Where can I find that in the spec?
so struct foo bar = {0} always initialises the first element of the first subelement of bar as if it had been initialised with = 0 and initialises the rest `[in] the same [way] as objects that have static storage duration'.
Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).
Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately. Note that char arrays can't be assigned with string, so they need to be copied explicitly with additional functions like memcpy or memmove (see manual).
When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
According to cppreference.com
If the number of initializer clauses is less than the number of members [and bases (since C++17)] or initializer list is completely empty, the remaining members [and bases (since C++17)] are initialized [by their default member initializers, if provided in the class definition, and otherwise (since C++14)] by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.
Foo
has no default member initializers (int b{0};
), so b
will be initialized by list-initialization with an empty list, which means value-initialization for non-class types: b = int() // = 0
.
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