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.
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.
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.
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.
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.
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.
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