If I have the following struct:
struct MyStruct {
int *a;
int *b;
};
And initializes it like this:
int some_var;
MyStruct s{
.a = &some_var
};
can I be sure s.b
will be initialized to nullptr
?
EDIT:
Full compiling code, tested with g++ 7.3.0:
// test.cpp
struct MyStruct {
int *a;
int *b;
};
int main()
{
int some_var;
MyStruct s{
.a = &some_var
};
}
If I print the variable values at this sample, b is indeed 0. But I want to know if this behavior is guaranteed by the standard.
Note, this is C99 syntax, which is not supported by C++11 standard, but supported by GCC. GCC documentation states so that that omitted field members are implicitly initialized the same as objects that have static storage duration.
Alternate syntax would be
MyStruct s{
a: &some_var
};
If the same field is initialized multiple times, it would be initialized with the value from the last initialization. If such initialization causes side-effect, it is unspecified whether the side effect happens or not. GCC discards them, only last initialization happens.
Here is C++11 compatible initialization:
MyStruct s { &some_var }; // second field would be initialized as one with static duration
GCC would issue a warning about missing initializers in both cases.