Is it possible to initialize a structure partially indicating the members?

3

In several languages it is possible to initialize a struct , or class, indicating which members want to put some value:

var obj = new Tipo { b = 1, e = "x" };

In C we can initialize the members in order:

Tipo obj = { 0, 1, 2, 'c', "x" };

But it does not work if you try some members by their names:

Tipo obj = { b = 1, e = "x" };

Can you do it?

    
asked by anonymous 17.01.2017 / 11:34

1 answer

2

In fact only the syntax is wrong. This works:

Tipo obj2 = { .b = 1, .e = "x" };

The point is important to differentiate the member identifier from the structure and a common variable.

This practice, called the designated initializer , can be problematic in C since the other members are not automatically initialized. This is why the technique is rarely used.

One thing that most people do not know is that you can do the structure assignment after the variable is declared. This does not work:

Tipo obj3;
obj3 = { .b = 1, .e = "x" };

But doing a cast to tell the compiler that the literal is the structure you want works:

Tipo obj3;
obj3 = (Tipo){ .b = 1, .e = "x" };

Obviously it works with all members without being named as well.

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
17.01.2017 / 11:34