Union – useless anachronism or useful old school trick?
You should be aware that in C++ they are not such a great solution, as only POD (plain old data) types can be placed in a union. If your class has a constructor, destructor, contains classes that have constructors and/or destructors (and about a million other gotchas), it cannot be a member of a union.
UNIONs implement some sort of polymorphism in a non-OOP world. Usually, you have a part which is common and depending on that part, you use the rest of the UNIONs. Therefore, in such cases where you do not have an OOP language and you want to avoid excessive pointer arithmetic, unions can be more elegant in some cases.
It's useful for setting bits in, say, registers instead of shift/mask operations:
typedef union {
unsigned int as_int; // Assume this is 32-bits
struct {
unsigned int unused1 : 4;
unsigned int foo : 4;
unsigned int bar : 6;
unsigned int unused2 : 2;
unsigned int baz : 3;
unsigned int unused3 : 1;
unsigned int quux : 12;
} field;
} some_reg;
Note: Which way the packing happens is machine-dependent.
some_reg reg;
reg.field.foo = 0xA;
reg.field.baz = 0x5;
write_some_register(some_address, reg.as_int);
I might have blown some syntax somewhere in there, my C is rusty :)
EDIT:
Incidentally, this works the opposite way also:
reg.as_int = read_some_register(some_address);
if(reg.field.bar == BAR_ERROR1) { ...
Indeed, it's a great tool when you write things like device drivers (a struct
that you want to send to device that can have several similar but different formats) and you require precise memory arrangement...