Stage 5

Custom Types Deep-Dive

typedef, enum, struct, union — four tools and the tagged-union pattern used in real embedded firmware.

5.1 typedef — naming existing types

typedef.c
typedef uint32_t Timestamp_ms;
typedef uint8_t  NodeId;

Timestamp_ms now   = 1000u;
NodeId       sensor = 3u;
  • Alias, not a new type. Timestamp_ms is uint32_t to the compiler. Timestamp_ms t = sensor; compiles — the safety is in the reader’s head, not the type checker.
  • Units in the name. _ms, _us, _mdeg, _counts are the cheapest unit system C has. Never name a time variable bare delay — is it ms, µs, or ticks?
typedef-pointer-trap.c — do not typedef bare pointers
typedef int *IntPtr;
IntPtr a, b;    /* a is int*, but b is ALSO int* — looks like "a is pointer, b is int" */
const IntPtr p; /* const int*? NO — int * const (const pointer, mutable data) */

Typedef-ing a pointer hides the * and inverts how const reads. If you must, name it …_ptr loudly — or better, keep the * visible at the declaration.

5.2 enum — named integer constants

enum.c
typedef enum {
    DIR_NORTH = 0,
    DIR_EAST,
    DIR_SOUTH,
    DIR_WEST
} Direction;
  • Values auto-increment from the previous one. Insert a new enumerator in the middle and every later value shifts — never persist raw enum values to flash, EEPROM, or a wire protocol without explicit values.
  • Underlying type is implementation-defined (usually int). sizeof(Direction) is typically 4, not 1 — use uint8_t explicitly if you need a 1-byte state field in a packed frame.
  • Bitmask enums use powers of two so values combine with |: FLAG_RX = 1u << 0, FLAG_TX = 1u << 1, FLAG_ERR = 1u << 2. Test with (flags & FLAG_ERR) != 0, never flags == FLAG_ERR.
  • Always handle the impossible case. A switch over an enum needs a default: — a corrupted byte can produce a value no enumerator names. Log it, do not ignore it.

5.3 struct — named composite type

struct.c
typedef struct {
    float    x, y, z;
    uint32_t timestamp;
} AccelSample;

AccelSample s = { .x=0.1f, .y=9.8f, .z=0.0f, .timestamp=1234 };
  • Structs copy by value. AccelSample t = s; copies every field (including padding bytes). Assignment and parameter passing are full copies — cheap for small structs, a hidden cost for large ones. Pass large structs by const pointer.
  • Comparison is not defined. s == t does not compile for structs. Compare field by field, or use memcmp only when you know padding bytes are identical (they usually are not — see Stage 6).
  • Designated initialisers (.x = …) survive field reordering; positional initialisers silently mis-assign when someone inserts a field. Always designate in production code.
  • Flexible array member (C99): uint8_t payload[]; as the last member of a struct, with the struct allocated as malloc(sizeof(Hdr) + len). One allocation, one free, header + payload together. Never declare it anywhere but last, and never take sizeof of the flexible member.

5.4 union & tagged union

tagged-union.c
typedef enum { MSG_TEMP, MSG_ACCEL, MSG_STATUS } MsgType;
typedef struct {
    MsgType type;
    union {
        float    temperature;
        AccelSample accel;
        uint8_t  status_code;
    } data;
} SensorMsg;
  • A union holds one member at a time. All members share the same memory; sizeof is the largest member’s size (plus alignment). Writing one member and reading another (“type punning”) is implementation-defined in C — it works in practice on GCC/Clang, but the defined way to reinterpret bytes is memcpy.
  • The tag is the contract. Every read must check msg.type first. Reading the wrong member is a logic bug the compiler cannot catch — which is why the tag exists.
  • Anonymous unions (C11) let you write msg.temperature instead of msg.data.temperature by omitting the member name. Same memory sharing, less nesting.
tagged-union-use.c — switch on the tag, handle every case
void handle_msg(const SensorMsg *msg) {
    switch (msg->type) {
        case MSG_TEMP:   printf("T=%.1f\n", (double)msg->data.temperature); break;
        case MSG_ACCEL:  printf("a=(%.2f,%.2f,%.2f)\n", (double)msg->data.accel.x,
                                (double)msg->data.accel.y, (double)msg->data.accel.z); break;
        case MSG_STATUS: printf("status=%u\n", msg->data.status_code); break;
        default:         /* corrupted / future tag: log, do not interpret */ break;
    }
}
⚠︎

Wire-format warning: a union’s layout still depends on padding and endianness (Stage 6). Never memcpy a whole SensorMsg onto a UART buffer — serialise field by field with shifts.