Lesson 28 / 38
Unions & Enums
Share memory between members with unions and name integer constants with enums.
A union: one slot, many types
A union's members all share the same memory — its size equals its largest member, and writing one member overwrites the others. Structs, by contrast, give each member its own space.
Union in action
Only the most recently written member holds a valid value.
union Data {
int i;
float f;
};
union Data d;
d.i = 10;
printf("%d\n", d.i); // 10
d.f = 3.14f;
printf("%d\n", d.i); // garbage now -- i was overwritten
Output:
10
Enums name constants
An enum lists related integer constants, starting at 0 by default, making code more readable than raw numbers.
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
enum Day today = WED;
printf("%d\n", today); // 2
Output:
2