Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The purpose of union with only one member inside the struct

I saw such union inside struct definition in pure c code in Linux kernel sources struct cma_multicast (it's not the only one place. Seems that it is some common practice):

struct cma_multicast {
    struct rdma_id_private *id_priv;
    union {
        struct ib_sa_multicast *ib;
    } multicast;
    struct list_head    list;
    void            *context;
    struct sockaddr_storage addr;
    struct kref     mcref;
};

But I can't figure out what is the purpose of union with only one member inside the struct? Why can't we just type struct ib_sa_multicast *ib; ?

I read this post but it has no usage explanation and has C++ specificity only.

UPD:
Posted example from Linux kernel instead of proprietary code.

like image 950
budoattack Avatar asked Aug 03 '20 12:08

budoattack


People also ask

What is the purpose of union in C?

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

When would you use a union over a struct?

You use a union when your "thing" can be one of many different things but only one at a time. You use a structure when your "thing" should be a group of other things.

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.

How is union inside structure defined?

A union is a user-defined type similar to structs in C except for one key difference. Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time.


1 Answers

This says in this case multicast can have only one polymorphic dispatcher.

It is object oriented programming made in C. The union is kept only for uniformity of naming.

like image 119
alinsoar Avatar answered Nov 16 '22 02:11

alinsoar