Stage 2
Custom Types Deep-Dive
typedef, enum, struct, union — four tools and the tagged-union pattern used in real embedded firmware.
2.1 typedef — naming existing types
typedef.c
typedef uint32_t Timestamp_ms;
typedef uint8_t NodeId;
Timestamp_ms now = 1000u;
NodeId sensor = 3u;2.2 enum — named integer constants
enum.c
typedef enum {
DIR_NORTH = 0,
DIR_EAST,
DIR_SOUTH,
DIR_WEST
} Direction;2.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 };2.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;