Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use c union nested in struct with no name

Tags:

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!

like image 929
zwx Avatar asked Nov 29 '12 11:11

zwx


People also ask

Can you define a structure without a name?

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.

How do you enter a union inside a struct?

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.

How do you use an anonymous union?

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.

Can we use union inside structure?

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.


2 Answers

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.

like image 74
Angew is no longer proud of SO Avatar answered Sep 22 '22 01:09

Angew is no longer proud of SO


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

like image 20
Atmocreations Avatar answered Sep 22 '22 01:09

Atmocreations