Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing struct with {0}

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?

like image 301
XPlatformer Avatar asked Oct 28 '19 12:10

XPlatformer


People also ask

Is struct initialized to 0?

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

Are global structs initialized to 0?

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

How do you initialize a struct value?

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

Can a struct be initialized?

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.


1 Answers

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.

like image 127
eike Avatar answered Sep 28 '22 07:09

eike