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


In many languages ​​it is possible to initialize a struct , or class, indicating which members you want to set some value to:

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 doesn't work if you try some members by their names:

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

Can you do it?


In fact only the syntax is wrong. Here's how it works:

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

The dot is important to differentiate the identifier of the structure member and a common variable.

This practice, called the assigned initiator , can be problematic in C since the other members are not automatically initialized. That's why the technique is little used.

One thing that a lot of people don't 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 indicate to the compiler that the literal is the structure you want, it works:

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

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

See working on ideone . And on Also posted on GitHub for future reference .

Scroll to Top