Lesson 27 / 36

Unions & Enums

A union shares memory; an enum names a set of integer constants.

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