Skip to chapter content
navan✳THE BUILD LABC17 / GUIDE
0/24 read
CHAPTER 14 / 21 · PROGRAM STRUCTURE

Unions, enums, and bit fields.

Represent alternatives and compact state without confusing storage with meaning.

BY NAVAN SAMILONG READC17 BASELINETHEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

An enum introduces named integer constants. It makes a finite set of conceptual states easier to read than unexplained numeric values, though the C type system does not enforce exhaustive handling of every enumerator. A union places several members in overlapping storage. It is useful when one value may have different representations at different times, but the program must know which member currently carries the intended value.

A tagged union pairs an enum tag with a union payload. The tag is the program's explicit promise about how to interpret the shared storage. This pattern can represent a measurement that is either a count or a temperature, or a message that is one of several variants. The compiler does not automatically keep tag and payload synchronized; constructors and access functions can make that invariant easier to maintain.

02 / THE RULES

What C guarantees.

Bit fields allocate named fields in an implementation-defined packing scheme. They can be convenient for local compact flags, but their exact layout, ordering, and alignment are poor foundations for portable file or network formats. For a stable external representation, use explicitly sized integers, shifts, masks, and documented byte order instead of copying a bit-field struct's raw bytes.

The example uses an enum to choose which union member is read. It stores an integer count and prints it only when the tag says that count is active. In a larger program, each case would have its own constructor and a switch that handles every declared state. That makes the relationship between state and payload reviewable rather than relying on a reader to infer it from unrelated assignments.

03 / UNDER THE SURFACE

Why the detail matters.

A tagged union is a convention layered over two language features. The enum has integer values and the union has overlapping members; the enclosing struct groups them. The compiler checks the syntax and member types, but it cannot prove that a COUNT tag always accompanies a count payload. Helper functions that set both fields together narrow the number of places where the invariant can be broken, and a switch can make interpretation branches easy to audit.

Bit fields are even more closely tied to implementation layout. Their allocation order and packing can differ, and taking the address of an individual bit field is not like taking the address of an ordinary member. Use them when a local in-memory compact representation is enough and the compiler's choices are acceptable. For a protocol, compute masks and shifts on a fixed-width unsigned integer and define the serialized byte order explicitly.

04 / CODE, EXPLAINED

See the rule in context.

unions-enums-and-bits.c
#include <stdio.h>

enum Kind { COUNT, TEMPERATURE };
struct Reading {
    enum Kind kind;
    union { int count; double temperature; } value;
};
int main(void) {
    struct Reading r = { .kind = COUNT, .value.count = 8 };
    if (r.kind == COUNT) printf("Count: %d\n", r.value.count);
    return 0;
}
FOLLOW THE EXECUTION

The designated initializer sets the tag to COUNT and the count member to 8. The condition confirms the intended interpretation before reading that member, so the program prints Count: 8. The temperature member occupies overlapping storage but is not used here. The tag and payload are separate fields; C does not stop code elsewhere from assigning an inconsistent pair.

05 / THE BOUNDARY

Where the rule stops.

A union is not a portable shortcut for reinterpreting arbitrary object representations. Reading a different member can have subtle or implementation-dependent consequences; use documented conversions or memcpy-based representation inspection where appropriate.

06 / THE CONNECTION

Keep this model.

This chapter models values inside one translation unit. The preprocessor and headers define how declarations are shared between files and how compile-time configuration can change what source the compiler sees.

Finished reading?
Built with curiosity. By Navan Sami. ↗C · Types, memory, and the rules behind the code.