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