Why Custom Data Types?
Raw integers and arrays can represent anything — but they tell you nothing about intent. Custom types add meaning, structure, and safety.
4.1 The grouping problem
uint8_t led_id = 1;
bool led_on = false;
uint8_t led_bright = 80;
uint32_t led_color = 0xFF8C00;
/* Nothing stops you from accidentally passing
led_color where led_id is expected. */typedef struct {
uint8_t id;
bool on;
uint8_t brightness;
uint32_t color;
} LedState;
LedState led = { .id=1, .on=false,
.brightness=80, .color=0xFF8C00 };4.2 Enum: named states
typedef enum {
SENSOR_IDLE,
SENSOR_MEASURING,
SENSOR_DATA_READY,
SENSOR_ERROR
} SensorState;
SensorState state = SENSOR_IDLE;4.3 Types are a correctness tool, not decoration
Grouping fields into a struct does more than tidy the code — it makes whole classes of mistakes unrepresentable or visible to the compiler:
- Wrong-argument bugs:
set_led(color, id)compiles silently when both areuint32_t.set_led(LedColor, LedId)with distinct types does not — or at least makes the swap obvious at the call site. - Unit bugs:
Timestamp_msvsTimestamp_us(see Stage 5) stops you adding milliseconds to microseconds without converting. The Mars Climate Orbiter lesson, in miniature. - Invalid states: an
enumwith four named states cannot hold “state 7”. A rawuint8_t statecan — and will, the day a corrupted byte arrives.
Honest limit: C’s type system is weak. typedef creates an alias, not a new type — Timestamp_ms and uint32_t are interchangeable to the compiler. Types help you and the reader; they do not enforce themselves the way Rust’s newtypes or Ada’s subtypes do. Treat them as documentation the compiler can partially check, not as a proof.
4.4 Values vs representation: the same bits, different meaning
The bit pattern 0x41 is simultaneously the character 'A', the number 65, and a bit mask with bits 0 and 6 set. The type decides the interpretation — which is why the same memory read through two different pointer types gives two different answers, and why casting a byte buffer to a struct is a portability bug (Stages 5–6).
uint8_t raw = 0x41;
char c = (char)raw; /* 'A' — same bits, character meaning */
int n = raw; /* 65 — same bits, numeric meaning */
bool b = raw != 0; /* true — same bits, truth meaning */
/* Endianness: the same 32-bit value, two byte orders on the wire. */
uint32_t v = 0x01020304; /* little-endian bytes: 04 03 02 01
big-endian bytes: 01 02 03 04 */Keep this picture in mind for every later lesson: types are the lens; memory is just bytes.