Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C99 Structure Designated Initialisers and other value

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.

like image 906
Sagrian Avatar asked Aug 19 '14 15:08

Sagrian


People also ask

What is designated initializers in C?

Designated initializers, a C99 feature, are supported for aggregate types, including arrays, structures, and unions. A designated initializer, or designator, points out a particular element to be initialized. A designator list is a comma-separated list of one or more designators.

What is designated initializer in Swift?

Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.


1 Answers

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 be f. We can look at paragraph 17 which says (emphasis mine):

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.129) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.130)

Why i is initialized to 0 is covered in paragrah 19 which says:

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;132) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

Note that as Keith points out gcc provides a warning for this using -Wextra:

warning: initialized field overwritten [-Woverride-init]
 struct myStruct m = {.f = 10.11, .c = 'a', 6}; 
        ^

and clang seems to warn about this by default.

like image 95
Shafik Yaghmour Avatar answered Sep 19 '22 10:09

Shafik Yaghmour