Unions, bitfields & undefined behavior
13 steps in 5 sets of C.
The parts of C that are legal, useful, and capable of ruining your week. Unions and struct layout, const and volatile and restrict, and then a set on undefined behavior itself.
Signed overflow, strict aliasing, sequence points: things that work until the optimizer notices it is allowed to assume they never happen. Thirteen steps, and it is the tour most likely to change how you read compiler warnings.
Unions & layout
- UnionsOne block of storage, several interpretations — but only one valid at a time.
- A tagged unionThe C way to write a sum type: an enum saying which member is live.
- BitfieldsStruct members measured in bits, for packing flags and small counters.
- offsetof and layoutoffsetof reports where a member sits, which is how intrusive containers work.
- Flexible array membersAn array of unknown length as the last member: one allocation for header and data.
Qualifiers
Undefined behavior
- Undefined behavior: signed overflowSigned overflow is undefined, so the compiler may assume it never happens.
- Undefined behavior: strict aliasingReading an object through an unrelated pointer type breaks the aliasing rule.
- More undefined behaviorShifting too far, reading uninitialized memory, dividing by zero — and the guards.
Escape hatches
- _GenericC11's type-based selection: one macro name, a different call per argument type.
- setjmp and longjmpA non-local jump back to a saved point — C's closest thing to an exception.
Encore
- value_interp.cA tiny stack machine built on a tagged union, with typed arithmetic.