Lesson 17: union & how it differs from struct
A struct gives every field its own memory — but C also has a thrifty twin: union. In a union all members share the same memory area, so only one of them is 'alive' at any moment. union Value { int i; double d; }; occupies the size of its largest member (8 bytes for the double), while a parallel stru
A struct is an apartment with a room for every tenant; a union is one room with one bed — when a new tenant moves in, the previous one is simply thrown out. At any moment exactly one lives there.
- union
- A type whose members all share the same memory area — only one member is valid at a time.
- shared memory (overlap)
- All union members start at the same location; writing to one overwrites the bits of the others.
- sizeof of a union
- The size of the largest member. In a struct, by contrast — roughly the sum of the members, sometimes more due to padding.
- padding
- Empty bytes the compiler adds to a struct to align fields in memory — so sizeof is sometimes larger than the sum of the fields.
- type tag
- A companion field (an int or enum) kept next to the union to remember which member is currently valid.