I am aware that in C99 you can initialize members of the structure using member name as follows :
struct myStruct
{
int i;
char c;
float f;
};
So following is valid :
struct myStruct m = {.f = 10.11, .i = 5, .c = 'a'};
Also it is said that uninitialised members will be set to 0
. So
struct myStruct m = {.f = 10.11, .c = 'a'};
here i
will be set to 0
But, for the following :
struct myStruct m = {.f = 10.11, .c = 'a', 6};
i
is still initialized to 0. What is the reason if we do such compound initialization.
In case of
the value
6
which is non-designated initializer will assign to the member just after the member initialized with designated initializer. So, in this case, memberf
is just afterc
and hence it will be initialized to6
.i
still will be initialized to0
by default.This is covered in the draft C99 standard section
6.7.8
Initialization, basically if the following initializer is not a designator then it will pick up with the next field after that designator, which for your examples would bef
. We can look at paragraph 17 which says (emphasis mine):Why
i
is initialized to0
is covered in paragrah 19 which says:Note that as Keith points out
gcc
provides a warning for this using-Wextra
:and
clang
seems to warn about this by default.Here, 6 is non-designated initializer. So, this value is initialized to the member just after the previous designated initializer, that is the float just after char.
In case you had two or more non-designated initializers in series, then the non-designated initializers would be initialized to the members in series from last designated initializer.