I'm working on the so called Hotspot open source project, and looking at the implementation I found a nasty nested union in struct looking like that:
typedef struct RC_model_t_st { union { struct block_model_t_st *block; struct grid_model_t_st *grid; }; /* block model or grid model */ int type; thermal_config_t *config; }RC_model_t;
As far as I'm aware in C/C++ that union is unaccesible. So how someone can make use of union declared in such manner and for what purpose?
Thanks!
Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions. Definition is just like that of a normal union just without a name or tag.
The unions are basically used for memory saving & it's size is equal to the largest member of the union. And for accessing the data fields of a union, use the dot operator(.) just as you would for a structure and explained by @Atmocreations.
An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared. You can use member names directly in the union scope without any additional member access syntax.
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
This is an anonymous union. In C++, as per [class.union], paragraph 5:
For the purpose of name lookup, after the anonymous union definition, the members of the anonymous union are considered to have been defined in the scope in which the anonymous union is declared
This means you can access its members as if they were members of RC_model_t_st
.
Without being sure and without having tried:
The union itself is not accessible, but it's members are.
Therefore you should be able to do refer to obj.block
and obj.grid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With