9

I saw such union inside struct definition in pure 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.

timrau
  • 22,578
  • 4
  • 51
  • 64
budoattack
  • 379
  • 3
  • 11
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/219214/discussion-on-question-by-budoattack-the-purpose-of-union-with-only-one-member-i). – Machavity Aug 04 '20 at 18:08

1 Answers1

2

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.

alinsoar
  • 15,386
  • 4
  • 57
  • 74