CC Explainer
C · 3 · Structs, Unions & I/O15 / 35 · 43%

typedef, Enums & Opaque Types

Name your types well, and hide implementation behind an opaque handle.

Examples: typedef struct, enum, forward declaration

shortcuts: ← prev · → next · M mark
1

typedef

Give a type a short, meaningful name.

Example
example
typedef struct Node Node;        // forward typedef
typedef unsigned long long u64;
typedef int (*Compare)(const void*, const void*);  // function pointer type
2

Enums

Named integer constants with automatic numbering.

Example
example
typedef enum {
    STATE_IDLE = 0,
    STATE_RUN,        // 1
    STATE_DONE,       // 2
    STATE_COUNT       // 3 — handy array size
} State;

const char *names[STATE_COUNT] = {"idle", "run", "done"};
TIP
A trailing COUNT member keeps lookup tables in sync automatically.
3

Opaque Handles

Expose a pointer type in the header, keep the struct body in the .c file.

Example
example
// stack.h
typedef struct Stack Stack;
Stack *stack_new(void);
void   stack_push(Stack *s, int v);
void   stack_free(Stack *s);

// stack.c
struct Stack { int *data; size_t len, cap; };
Callers can't touch the fields, so you can change the layout without breaking them.
4

Union Tricks

A union stores one member at a time in the same bytes.

Example
example
typedef struct {
    enum { T_INT, T_FLT, T_STR } tag;
    union { int i; float f; char *s; } as;
} Value;   // tagged union — always check tag before reading