C: Unions and Enumerations
A union is like a multi-purpose charging cable — you can only use one interface at a time, but it saves space. An enum is like a menu number — using names instead of raw numbers makes code more readable.
1. union Definition and Shared Memory
All members of a union share the same memory. Its size equals the size of its largest member. Only one member can be used at a time.
// Struct/enum/union definition
union Data {
// Variable declaration
int i;
// Variable declaration
float f;
char str[4];
};
// I/O operation
printf("%zu\n", sizeof(union Data));
4
After assigning to the int member, reading the float member gives a different interpretation of the same memory:
union Data d;
d.i = 42;
// I/O operation
printf("i = %d\n", d.i);
// I/O operation
printf("f = %f\n", d.f);
i = 42
f = 0.000000
2. union vs. struct
| Feature | struct | union |
|---|---|---|
| Memory | Each member has its own space | All members share the same space |
| Size | Sum of all member sizes (with alignment padding) | Size of the largest member |
| Simultaneous access | All members can be accessed at the same time | Only one member at a time |
| Modification | Changing one doesn't affect others | Changing one affects all |
// Struct/enum/union definition
struct SData {
// Variable declaration
int i;
// Variable declaration
float f;
char str[4];
};
// Struct/enum/union definition
union UData {
// Variable declaration
int i;
// Variable declaration
float f;
char str[4];
};
// I/O operation
printf("struct: %zu\n", sizeof(struct SData));
// I/O operation
printf("union: %zu\n", sizeof(union UData));
struct: 12
union: 4
3. Tagged Unions
In practice, unions are typically paired with a tag field that indicates which type is currently stored:
// Type definition
typedef struct {
// Variable declaration
int type;
union {
// Variable declaration
int int_val;
// Variable declaration
float float_val;
char str_val[32];
} value;
} Variant;
// Function definition
void print_variant(const Variant *v) {
// Switch statement
switch (v->type) {
// Case branch
case 0: printf("int: %d\n", v->value.int_val); break;
// Case branch
case 1: printf("float: %f\n", v->value.float_val); break;
// Case branch
case 2: printf("str: %s\n", v->value.str_val); break;
}
}
▶ Example
▶ Try it Yourselfint: 42
double: 3.14
4. enum Definition and Usage
Enumerations use names instead of integer constants, improving code readability.
// Struct/enum/union definition
enum Color {
RED,
GREEN,
BLUE
};
enum Color favorite = GREEN;
// Conditional check
if (favorite == GREEN) {
// I/O operation
printf("Green selected\n");
}
Green selected
(1) Specifying Enum Values
// Struct/enum/union definition
enum Weekday {
MON = 1,
TUE,
WED,
THU,
FRI,
SAT = 100,
SUN
};
// I/O operation
printf("MON=%d SAT=%d SUN=%d\n", MON, SAT, SUN);
MON=1 SAT=100 SUN=101
(2) enum with switch
// Struct/enum/union definition
enum Direction { UP, DOWN, LEFT, RIGHT };
// Function definition
void move(enum Direction d) {
// Switch statement
switch (d) {
// Case branch
case UP: printf("Move up\n"); break;
// Case branch
case DOWN: printf("Move down\n"); break;
// Case branch
case LEFT: printf("Move left\n"); break;
// Case branch
case RIGHT: printf("Move right\n"); break;
}
}
int — you can assign any integer value, and the compiler may not warn. Don't abuse this feature.
5. Underlying int Values of Enums
Enum constants are essentially named constants of type int.
// Struct/enum/union definition
enum Status { OK = 200, NOT_FOUND = 404, ERROR = 500 };
// I/O operation
printf("%d %d %d\n", OK, NOT_FOUND, ERROR);
200 404 500
Enum variables can be assigned to and from integers (in C), but it's best to use enum values for type consistency:
enum Status s = OK;
// Variable declaration
int code = s;
#define for constants: enums have type information, display symbolic names in debuggers, and have more controllable scope.
6. Using union to Detect Endianness
Endianness refers to the byte order of multi-byte data in memory. A union makes it easy to detect:
// Function definition
int is_little_endian(void) {
union {
// Variable declaration
int i;
// Variable declaration
char c;
} u;
u.i = 1;
// Return result
return u.c == 1;
}
If the lowest byte is stored at the lowest address (u.c == 1), it's little-endian; otherwise it's big-endian.
▶ Example
▶ Try it YourselfMemory byte order: 78 56 34 12
Little Endian
7. union for Memory Savings in Practice
When a struct has multiple mutually exclusive fields, use a union to save space:
// Type definition
typedef struct {
// Variable declaration
int type;
union {
struct { int width, height; } rect;
struct { int radius; } circle;
struct { int side; } square;
} shape;
} Figure;
Figure f;
f.type = 1;
f.shape.circle.radius = 10;
Only one of the three shapes is used at a time. The union shares memory, and the struct size is determined by the largest shape.
▶ Example 3: Detecting Endianness with a Union
▶ Try it Yourself输出(little-endian, e.g., x86):
TEXTByte order: 04 03 02 01 This is a little-endian system.
❓ FAQ
typedef enum { RED, GREEN, BLUE } Color; creates both an enum type named (anonymous in this case) and a typedef alias Color. After that you can write Color c = RED; without the enum keyword. This is why typedef is so common with both enums and structs.const char *color_names[] = {"Red", "Green", "Blue"}; and index into it.📖 Summary
- All union members share memory; the size equals the largest member; only one member is used at a time
- In practice, unions are paired with a tag field (tagged union) to distinguish the currently valid type
- enum replaces magic numbers with named constants, improving readability; the underlying type is int
- Enum values default to incrementing from 0; you can manually specify any int value
- A union can detect system endianness — the byte storage order of multi-byte data
📝 Exercises
- Define
union IPAddresscontainingunsigned int addrandunsigned char bytes[4]. Input an IP integer value and output it as both an integer and four separate bytes - Define an enum
enum Season { SPRING, SUMMER, AUTUMN, WINTER }and write a function that returns the corresponding season name string based on the enum value - Use a tagged union to implement a simple shape struct with a type tag and union (rectangle/circle), then write a function to calculate the area