← C ProgrammingC PROGRAMMING 1.4

Structs and Unions

Composite types, including the bit-field and union patterns that show up constantly in register/protocol code.

Structs and unions — how to bundle related values into one type, and then how to reach straight into a register's individual bits using nothing but struct syntax.

The six chapters

  • A — Struct Basics. Declaration, member access, initialization.
  • B — Structs and Pointers. Pointer-to-struct, -> vs (*p).field, and passing structs by pointer instead of copying the whole thing.
  • C — Nested & Advanced Structs. Structs containing structs, and what that does to the actual memory layout.
  • D — typedef. Naming struct and pointer types so they read cleanly instead of repeating struct foo everywhere.
  • E — Bit Fields. Packing sub-byte fields into a struct — the exact pattern a register map is usually described with.
  • F — Unions. Shared storage between members, type punning, and where that's actually safe versus where it's asking for trouble.

Where this lands in driver work

This is the chapter register maps and protocol headers are written in. A hardware register described as "bits 0-2 are mode, bit 3 is enable, bits 4-7 are reserved" is a bit-field struct overlaid on a volatile uint32_t; a packet header is a struct whose layout has to match the wire format byte for byte.

Notes from readers

Comments — via GitHub