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

Asked

Viewed 61 times

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 members in order:

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

But it doesn’t work if you try a few members by their names:

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

Can do?

1 answer

2


Actually only the syntax is wrong. So it 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 designated initiator, can be problematic in C since the other members are not initialized automatically. Therefore the technique is little used.

One thing a lot of people don’t know is that you can do structure assignment after you’ve declared the variable. This doesn’t work:

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

But making a cast to indicate to the compiler that the literal is the structure you want, works:

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

It obviously works with all members without being appointed as well.

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • And if one of the members is a pointer, the ->?

  • In this case the initialization is by right value, in the case of the pointer would be by reference using the arrow ->, correct?

  • @cat not really because this is a syntax only to disambiguate member of the structure and a normal variable that may have the same name. http://ideone.com/4E3HCn

Browser other questions tagged

You are not signed in. Login or sign up in order to post.