Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nameless union inside a union

Tags:

c

unions

I'm reading some code and found something like the following:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union {
        struct foo *a;
        struct foo *b;
        struct foo *c;
    };
} type_t;

From syntax point of view, the inner union {} can be removed and having *a, *b and *c directly inside the outer union {}. So what's the purpose the namelessly embedded union?

like image 354
lang2 Avatar asked Mar 14 '14 13:03

lang2


People also ask

Can we have 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.

What is the difference between a union and an anonymous union?

An anonymous union is a union without a name. It cannot be followed by a declarator. 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.

What nested union?

Nested Union is Union which has another Union as a member in that Union. A member of Union can be Union itself , this what we call as Nested Union.

Why do we use union inside structures in C?

A union is an object similar to a structure except that all of its members start at the same location in memory. A union variable can represent the value of only one of its members at a time. In C++, structures and unions are the same as classes except that their members and inheritance are public by default.


1 Answers

Unnamed union/struct inside another union/struct is a feature of C11, and some compiler extensions (e.g, GCC).

C11 §6.7.2.1 Structure and union specifiers

13 An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure; an unnamed member whose type specifier is a union specifier with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.

The advantage of this feature is that one can access its unnamed union field easier:

type_t x;

To access the field a, you can simply use x.a. Compare with the code without using this feature:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union u{      //difference in here
    struct foo *a;
    struct foo *b;
    struct foo *c;
    };
} type_t;

type_t x;

You need to use x.u.a.

Related: unnamed struct/union in C

like image 109
Yu Hao Avatar answered Oct 01 '22 20:10

Yu Hao