Initializing Nested Structures
- Richard Hammond
- Jul 26, 2016
- 2 min read
The other week I wanted to specify default values for members of a structure using designated initializers. Normally this would be a trivial task. However, a couple of constraints made this tricky. First of all it was an anonymous structure, second it was nested within a union, and third it was legacy code so I could not typedef the struct (which would've taken care of the anonymous structure issue). Here is an example of what I was dealing with:

Solving the Problem
The first thing I tried to do was implicitly initialize the nested structure by doing the following:

The first curly brackets select the union as the current object. Once "combined_example" was assigned, another pair of curly brackets were used to select the anonymous structure as the current object. However, since I was initializing a union, only one member of the union could be initialized. Since the structure is anonymous, I was not able to use designated initializers for the members of the union. This means implicit initializers had be used. Implicit initializers require members to be initialized in order. The only way I found to implicitly initialize the structure was to flip the problem upside down.

After flipping the order of the union, the compiler had enough context to implicitly initialize the structure and only the structure. This allowed me to meet the requirements of only initializing one object in a union, and solves the original goal. If the struct could have been named, designated intitializers could have easily been used, and the order of the union could have stayed the same.
Still curious about initializing structures? Here are my sources:
Have any questions, suggestions, or anything you disagree with? Leave a comment below!
Comments