typestar

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.

Start this tour

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

  • volatilevolatile tells the compiler the value can change behind its back.
  • restrictrestrict promises the pointers do not overlap, which lets the compiler optimize.

Undefined behavior

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.

The other C tours