Unions & enums
8 min lesson
- A union stores different types in the same memory, so only one member is valid at a time; an enum gives names to a fixed set of integer constants.
- They matter because unions save memory when only one of several values is needed at once, and enums make code readable by replacing magic numbers with names.
- Think of a union as one drawer that can hold a fork or a knife but not both at once; an enum is like a menu with a fixed list of dishes, each with a number.
- A union is declared like a struct with the union keyword, but all members share the same memory, so writing one overwrites the others.
- An enum is declared with the enum keyword and a list of names; the first is 0 by default, the next is 1, and so on.
- The size of a union is the size of its largest member; the size of an enum is usually the size of an int.
- The computer reserves one block for the union and lets each member interpret those bytes; the enum is just named integer constants at compile time.
- The syntax is: union U { int i; float f; }; and enum Color { RED, GREEN, BLUE };.
- A realistic use: a union for a value that can be an int or a float, and an enum for the days of the week or a status code.
- A surprising detail: reading a union member other than the last one written is undefined behavior in general, though it is sometimes used intentionally for bit tricks.
- The example program uses an enum for colors and a union to hold either an int or a float, showing that only the last written member is valid.
- Use a union only when you know which member is active at any time.
- Use an enum to replace magic numbers with clear names.
- Remember that writing one union member overwrites the others.
- Enums can be assigned any integer value in C, so validate when it matters.
- These tools round out your data toolkit. Great job!
#include <stdio.h>
// An enum with three named colors; RED=0, GREEN=1, BLUE=2
enum Color { RED, GREEN, BLUE };
// A union that can hold an int or a float, not both at once
union Value {
int i;
float f;
};
int main(void) {
// Use the enum like a small integer with a clear name
enum Color favorite = GREEN;
// Print the numeric value behind the name
printf("Favorite color value: %d\n", favorite);
// A union variable: only one member is valid at a time
union Value v;
// Write the int member first
v.i = 42;
printf("As int: %d\n", v.i);
// Write the float member, which overwrites the int
v.f = 3.5f;
printf("As float: %.1f\n", v.f);
return 0;
}What happens: Favorite color value: 1 As int: 42 As float: 3.5
Breaking it down
Enum definition
enum Color { RED, GREEN, BLUE };Creates three named constants. RED is 0, GREEN is 1, BLUE is 2. You can use these names in place of numbers.
Using the enum
enum Color favorite = GREEN;Stores the value 1 under the readable name GREEN. The compiler sees the integer value.
Union definition
union Value { int i; float f; };Declares two members that share the same memory. The union is as big as its largest member.
Writing one member
v.i = 42;Stores 42 in the shared memory. At this moment, only i is valid.
Writing another member
v.f = 3.5f;Overwrites the shared memory with a float. The previous int value is gone; reading v.i now would be meaningless.
Union vs enum
| Feature | union | enum |
|---|---|---|
| Purpose | Share memory between types | Name a set of integers |
| Size | Largest member size | Usually int size |
| Access | One member valid at a time | Any named constant |
| Example | union { int i; float f; } | enum { RED, GREEN } |
A helpful analogy
A union is like a single drawer that can hold a fork or a knife, but not both at once. If you put a fork in and then a knife, the fork is gone. An enum is like a menu with a fixed list of dishes, each with a number so you can order by name instead of by number.
Nesting rules
- 1.Only the last-written union member is valid; reading another is undefined behavior in general.
- 2.Use unions when memory is tight and only one value is needed at a time.
- 3.Enum constants are integers; you can assign them to int variables, but be careful with type checks.
- 4.Give enum values explicit numbers when the exact values matter, like enum { OK = 200, NOT_FOUND = 404 };.
Common mistakes
Reading a union member that was not last written
Avoid
v.i = 42;
v.f = 3.5f;
printf("%d", v.i); // garbageUse instead
track which member is active, or use a struct with a tagThe float overwrote the int's bytes. Reading v.i gives a meaningless value. Use a tagged struct if you need to know which member is active.
Assuming enum values are always 0, 1, 2
Avoid
enum E { A = 5, B, C }; // B is 6, not 1Use instead
enum E { A = 0, B = 1, C = 2 };Enum values continue from the last explicit value. Assign explicit numbers when the exact values matter.
Using a union when all members are needed at once
Avoid
union { int x; int y; } p; // cannot hold bothUse instead
struct { int x; int y; } p;Union members share memory, so writing y destroys x. Use a struct when you need every member to stay valid.
Quick tips
- •Pair a union with an enum tag in a struct to remember which member is active.
- •Use enums instead of magic numbers like 0, 1, 2 in your code.
- •Print enum values with %d to see the underlying integer.
- •Try changing the enum order and rerun to see the new values.
- •Remember the union size equals its largest member; print sizeof to check.