The Analogy: One Parking Space, and a Numbered List of Options
A union is a single parking space that fits a motorbike, a car, or a van — but only one at a time. All three members start at the same address and share the same bytes, so the space is only as big as the largest vehicle. Park the van and the motorbike is gone. Crucially, the space keeps no record of what is currently parked in it; that is your job.
An enum is the printed list on the wall: BIKE, CAR, VAN — names for the integers 0, 1 and 2. It costs nothing at run time (the compiler substitutes the numbers) but turns if (kind == 1) into if (kind == CAR), which is the difference between code you can read and code you have to decode.
The two are made for each other. A union stores one of several shapes; an enum records which shape it is. Put them in a struct together and you have a tagged union — C's answer to "this value is a number, or a string, or a flag, and I need one type that can hold any of them".
Syntax or Core Structure
#include <stdio.h>
enum Status { STATUS_IDLE, STATUS_RUNNING, STATUS_DONE }; /* 0, 1, 2 */
enum Level { LEVEL_LOW = 10, LEVEL_MID = 20, LEVEL_HIGH = 30 };
union Value {
int i;
double d;
char text[8];
};
struct AllThree { /* the same members, not shared */
int i;
double d;
char text[8];
};
int main(void) {
enum Status s = STATUS_RUNNING;
printf("status %d of %d\n", (int)s, (int)STATUS_DONE);
printf("levels: %d %d %d\n", LEVEL_LOW, LEVEL_MID, LEVEL_HIGH);
union Value v;
v.i = 42;
printf("as int: %d\n", v.i);
v.d = 2.5; /* the double is the live member now */
printf("as double: %.1f\n", v.d);
snprintf(v.text, sizeof v.text, "%s", "hello");
printf("as text: %s\n", v.text);
printf("sizeof union = %zu, sizeof struct = %zu\n",
sizeof(union Value), sizeof(struct AllThree));
return 0;
}
Output:
status 1 of 2
levels: 10 20 30
as int: 42
as double: 2.5
as text: hello
sizeof union = 8, sizeof struct = 24
The last line is the whole point. The union is 8 bytes — big enough for its largest member, the double (the char[8] ties it) — while the struct is 24: 4 for the int, 4 of padding, 8 for the double, 8 for the array. Sizes assume a typical 64-bit desktop compiler; the relationship holds everywhere.
Note also what did not happen: after v.d = 2.5, nothing warned that v.i was now meaningless. The bytes of 42 were simply overwritten.
Technical Depth: Shared Bytes and Named Integers
| Question | struct | union |
|---|---|---|
| Where do members live? | one after another | all at offset 0 |
sizeof | sum of members plus padding | size of the largest member, rounded to its alignment |
| How many members are usable? | all of them | one, the one written most recently |
| What does assignment copy? | every member | the whole shared block of bytes |
Initialiser { 1 } | sets the first member | sets the first member, and that member becomes live |
Only the last member written may be read
union Value v;
v.i = 1078530011;
printf("%f\n", v.d); /* reinterprets those bytes as a double */
C allows this — unlike C++ — but what you get back depends on the size, byte order and floating-point format of the machine, and for some types the bytes may not form a valid value at all. It is a portability hole, not a feature. When you genuinely want to reinterpret bytes, say so explicitly with memcpy into a variable of the target type; the compiler optimises it away and the intent is visible to the next reader.
A union has no idea what is in it
This is the defining limitation, and the reason the tagged-union pattern exists:
typedef enum { SHAPE_CIRCLE, SHAPE_RECT } ShapeKind;
typedef struct {
ShapeKind kind; /* the tag: which member is live */
union {
double radius;
struct { double w, h; } rect;
} u;
} Shape;
double area(const Shape *s) {
switch (s->kind) {
case SHAPE_CIRCLE: return 3.14159265 * s->u.radius * s->u.radius;
case SHAPE_RECT: return s->u.rect.w * s->u.rect.h;
}
return 0.0; /* kind was not a listed value */
}
The invariant "the tag always matches the live member" is not checked by anything. It is maintained by making every write go through a constructor function that sets both fields together, never by hand at call sites.
Enums are names for int, and nothing more
enum Weekday { MON, TUE, WED, THU, FRI }; /* 0..4 */
enum Odd { A = 1, B, C = 1, D }; /* 1, 2, 1, 2 — duplicates are legal */
enum Weekday d = 99; /* accepted; 99 is not a Weekday */
int n = FRI; /* fine: enum constants are ints */
Unspecified values continue from the previous constant, so B is 2 and D is 2. Duplicate values are allowed, duplicate names are not: enum constants share one namespace with ordinary identifiers, so two different enums cannot both define OK. That is why real codebases prefix them — STATUS_DONE, LEVEL_HIGH.
An enum variable can hold any value its underlying integer type can, so a switch over one still needs a default or a trailing return for the unlisted case. Do not assume the size either; before C23 the underlying type is implementation-defined, and %d with an explicit (int) cast is the safe way to print one.
Why bother, when #define exists?
enum | #define | |
|---|---|---|
| Visible in a debugger | yes, by name | no, the text is gone before compiling |
| Auto-numbering | yes | you maintain the numbers |
-Wswitch warns on a missing case | yes | no |
| Can be any type | integers only | any token sequence |
For a closed set of related integer options, enum wins on every line that matters. The -Wswitch row is the sleeper: add a new constant and every switch that forgot to handle it lights up at compile time, provided you resist the urge to add a default that silently swallows new cases.
Real World Example: A Settings Table That Holds Mixed Types
Configuration is the classic case: max_retries is an integer, timeout is a real number, log_path is text, verbose is a flag. One array has to hold all four.
#include <stdio.h>
#include <string.h>
typedef enum { VAL_INT, VAL_REAL, VAL_TEXT, VAL_BOOL } ValueKind;
typedef struct {
char name[16];
ValueKind kind; /* which member of u is live */
union {
long as_int;
double as_real;
char as_text[24];
int as_bool;
} u;
} Setting;
struct Separate { /* the same fields without the union */
char name[16];
ValueKind kind;
long as_int;
double as_real;
char as_text[24];
int as_bool;
};
static const char *kind_name(ValueKind k) {
switch (k) {
case VAL_INT: return "int";
case VAL_REAL: return "real";
case VAL_TEXT: return "text";
case VAL_BOOL: return "bool";
}
return "?"; /* an out-of-range kind */
}
static void print_setting(const Setting *s) {
printf("%-12s %-5s ", s->name, kind_name(s->kind));
switch (s->kind) {
case VAL_INT: printf("%ld\n", s->u.as_int); break;
case VAL_REAL: printf("%.2f\n", s->u.as_real); break;
case VAL_TEXT: printf("[%s]\n", s->u.as_text); break;
case VAL_BOOL: printf("%s\n", s->u.as_bool ? "yes" : "no"); break;
default: printf("corrupt\n"); break;
}
}
/* Refuses rather than reinterpreting: the tag is the only safe gate. */
static int setting_get_long(const Setting *s, long *out) {
if (s == NULL || out == NULL || s->kind != VAL_INT) return -1;
*out = s->u.as_int;
return 0;
}
static const Setting *find_setting(const Setting *t, size_t n, const char *name) {
for (size_t i = 0; i < n; i++)
if (strcmp(t[i].name, name) == 0) return &t[i];
return NULL;
}
The table sets the tag and the value on the same line, which is the discipline that keeps them in step:
int main(void) {
const Setting table[] = {
{ .name = "max_retries", .kind = VAL_INT, .u.as_int = 5 },
{ .name = "timeout", .kind = VAL_REAL, .u.as_real = 2.75 },
{ .name = "log_path", .kind = VAL_TEXT, .u.as_text = "/var/log/app.log" },
{ .name = "verbose", .kind = VAL_BOOL, .u.as_bool = 0 },
};
const size_t count = sizeof table / sizeof table[0];
for (size_t i = 0; i < count; i++)
print_setting(&table[i]);
putchar('\n');
const char *wanted[] = { "max_retries", "timeout" };
for (size_t i = 0; i < 2; i++) {
const Setting *s = find_setting(table, count, wanted[i]);
long n;
if (s != NULL && setting_get_long(s, &n) == 0)
printf("%s as int: %ld\n", wanted[i], n);
else
printf("%s as int: refused\n", wanted[i]);
}
printf("sizeof(Setting) = %zu (%zu with four separate fields)\n",
sizeof(Setting), sizeof(struct Separate));
return 0;
}
Output:
max_retries int 5
timeout real 2.75
log_path text [/var/log/app.log]
verbose bool no
max_retries as int: 5
timeout as int: refused
sizeof(Setting) = 48 (72 with four separate fields)
Three things to take from this:
timeoutis refused, not reinterpreted.setting_get_longchecks the tag first, so a caller asking for the wrong type gets-1instead of the bit pattern of 2.75 read as along. Without that check the program would print a large meaningless number and keep going.- The union pays for itself as the type list grows. 48 bytes against 72 here; across a thousand records that is 24 KB, and the gap widens with every new variant, because the union costs the largest member while the struct costs the sum.
- The
switchinprint_settinghas nodefaultfor the four real cases. AddingVAL_LISTto the enum makes-Wswitchpoint straight at every function that needs updating. Thedefaultthat is there catches only genuinely out-of-range tags — say, a struct that was never initialised.
One deliberate limit: as_text is a fixed char[24], not a char *. A pointer member would make the union 8 bytes smaller but would raise the question of who owns the string, and freeing the pointer when the tag says VAL_INT is exactly the crash this design avoids.
Common Mistakes
- Reading a member you did not write last. Storing
v.iand readingv.dreinterprets bytes; the result depends on size, byte order and floating-point format, and may not be a valid value at all. Usememcpywhen reinterpretation is the actual goal. - Expecting the union to remember. There is no hidden field recording which member is live. If your code needs to know, you must store a tag alongside it.
- Updating the value without updating the tag.
s->u.as_real = 2.75;on a setting still taggedVAL_INTproduces a struct that lies about itself. Write both in one function so they cannot drift apart. - Assuming
sizeofa union is the sum of its members. It is the size of the largest, padded to the alignment it needs — that is the entire reason to use one. - Freeing a pointer member without checking the tag. If one variant is
char *and another islong, callingfreeon the wrong variant hands the allocator an integer. Prefer a fixed array, or make ownership part of the tag's contract. - Reusing a constant name across two enums. Enum constants live in the ordinary identifier namespace, so a second
OKis a redefinition error. Prefix them with the enum's purpose. - Trusting that an enum variable holds a listed value. Any integer in range can be assigned, including from a cast or a file read. A
switchover one still needs a fallback, and values arriving from outside the program need validating. - Depending on an enum's size or signedness. Before C23 the underlying type is implementation-defined, so do not write it to a binary file, compare its
sizeoftoint, or pass it toprintfwithout an explicit(int)cast.
Best Practices
- Reach for a union only when the variants are genuinely exclusive; if two can be true at once, you want a struct.
- Pair every union with a tag in an enclosing struct, and treat "the tag matches the live member" as the type's one invariant.
- Funnel all writes through small constructor functions that set the tag and the value together.
- Make accessors check the tag and return an error code rather than reinterpreting bytes on a mismatch.
- Use
enuminstead of#definefor a closed set of related integers — you gain debugger names, automatic numbering and-Wswitch. - Prefix enum constants (
STATUS_DONE,VAL_TEXT) because they share one namespace with every other identifier. - Leave the
defaultoff aswitchthat means to handle every constant, so the compiler tells you when a new one appears; add one only for genuinely invalid values. - Use
memcpy— not a union — when you deliberately want to view the same bytes as another type, and say why in a comment.
Practice Exercises
- Watch the bytes overlap. Declare
union Value { int i; double d; char text[8]; };, print&v.i,&v.dand(void *)v.textand confirm all three are the same address. Then writev.i = 1078530011, printv.d, and print all 8 bytes withunsigned char *p = (unsigned char *)&v;and%02x. Write down which bytes changed and which kept old contents, and explain what the byte order tells you about your machine. - A tagged shape. Build
ShapeKindwithSHAPE_CIRCLE,SHAPE_RECTandSHAPE_TRIANGLE, aShapestruct holding a tag and a union, constructorsmake_circle,make_rectandmake_trianglethat set both fields, and anareafunction using aswitchwith nodefault. Compile with-Wall -Wextra, then add a fourth kind without touchingareaand record the warning you get. Verify each area against a figure you calculated by hand. - Extend the settings table. Add
VAL_LISTholdingstruct { int items[4]; int count; }to the example, updatekind_nameandprint_setting, and add a"ports"row containing 80, 443 and 8080. Print the newsizeof(Setting), explain in one sentence why it changed by the amount it did, and addsetting_get_realthat refuses any tag other thanVAL_REAL— then show it refusinglog_path.