Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason for using unions today (when we have so much available memory)?

Tags:

c

unions

As I understand it, unions are a way to use memory chunk for several purposes. Is there a reason to use a union in our days, where memory is not an issue?

Obviously my question does not regard using limited HW that can be found on some small embedded devices.

like image 209
CIsForCookies Avatar asked Dec 21 '25 14:12

CIsForCookies


2 Answers

Arguably, saving space is a side effect of defining a union. The primary reason for having a union is enabling creation of structures with only one active member at any given time.

struct StringOrInt {
    enum {String, Int} kind;
    union {
        char *str;
        int num;
    } val;
};

Although one could argue that union above could be replaced with struct when memory is not an issue, this would misrepresent the purpose of the structure to readers of the code, who would assume that both str and num could be set under some valid circumstances. Using union, on the other hand, makes it clear to the code readers that the intention is to set either str or num, but never both of them at the same time.

like image 172
Sergey Kalinichenko Avatar answered Dec 24 '25 04:12

Sergey Kalinichenko


There is reason. I have seen codes even now which use them as variant types.

struct my_vartype_t {
    int type;
    union {
        char char_value;
        int int_value;
    };
};

Now based on the type it will use necessary union value. This is a very trivial example here but it is used in many cases to provide a code with compact data association ( by this we mean that not scattering unnecessary redundant types rather one clean way to the variant type).

As mentioned by AndrewHenle these are some examples of using unions in real-world XEvent, struct sockaddr.

like image 28
user2736738 Avatar answered Dec 24 '25 03:12

user2736738