name: c-macros description: C macro patterns — DeferLoop for RAII-like cleanup, X-macros, for-each iterators, named parameters, type-generic macros. Use when: writing C macros, reducing boilerplate, code generation. license: MIT
C Macro Patterns
Macros are C's metaprogramming tool. Use them to reduce boilerplate, generate repetitive code, and create domain-specific patterns.
DeferLoop (RAII-like Cleanup)
Execute cleanup code when a scope exits, similar to RAII in C++ or defer in
Go.
Implementation
#define DeferLoop(begin, end) \
for (int _i_ = ((begin), 0); !_i_; _i_ += 1, (end))
Usage
// Automatic mutex release
void process_data(void)
{
DeferLock(mutex_take(&data_mutex), mutex_drop(&data_mutex))
{
// Critical section - mutex automatically released on exit
data->counter++;
}
}
// Scoped locking macro
#define MutexScope(mutex) DeferLoop(mutex_take(mutex), mutex_drop(mutex))
void update_shared(void)
{
MutexScope(data_mutex)
{
// Automatically releases mutex
}
}
// File handle cleanup
void read_config(void)
{
FILE *f = 0;
DeferLoop(f = fopen("config.txt", "r"), (f && fclose(f)))
{
if (f) {
// Read file...
}
}
}
// Arena scope
#define ArenaTempScope(arena) \
U64 _pos_##__LINE__ = arena_pos(arena); \
DeferLoop((void)0, arena_pop_to(arena, _pos_##__LINE__))
For-Each Iterators
Clean iteration over arrays, ranges, and data structures.
Index Iterators
#define EachIndex(it, count) \
for (U64 it = 0; it < (count); it += 1)
#define EachElement(it, array) \
for (U64 it = 0; it < ArrayCount(array); it += 1)
#define EachInRange(it, range) \
for (U64 it = (range).min; it < (range).max; it += 1)
Enum Iterators
#define EachEnumVal(type, it) \
for (type it = (type)0; it < type##_COUNT; it = (type)(it + 1))
// Usage
typedef enum Color { Color_Red, Color_Green, Color_Blue, Color_COUNT } Color;
EachEnumVal(Color, c)
{
const char *name = color_names[c];
printf("%s\n", name);
}
Node Iterators
#define EachNode(it, first) \
for (Node *it = (first); it != 0; it = it->next)
#define EachNodeSafe(it, first, next) \
for (Node *it = (first), *next = it ? it->next : 0; it != 0; it = next, next = it ? it->next : 0)
// Usage
for EachNode(node, list->first)
{
process(node);
}
X-Macros
Define data once, expand it multiple ways. Eliminates duplication and ensures consistency.
Pattern
// 1. Define the data (not compiled directly)
#define COLOR_LIST \
X(Red, 0xFF0000) \
X(Green, 0x00FF00) \
X(Blue, 0x0000FF)
// 2. Expand to enum
typedef enum Color {
#define X(name, value) Color_##name,
COLOR_LIST
#undef X
Color_COUNT
} Color;
// 3. Expand to string table
const char *color_names[] = {
#define X(name, value) [Color_##name] = #name,
COLOR_LIST
#undef X
};
// 4. Expand to value table
U32 color_values[] = {
#define X(name, value) [Color_##name] = value,
COLOR_LIST
#undef X
};
Struct Generation
#define HEADER_FIELDS \
X(U64, magic) \
X(U32, version) \
X(U32, flags) \
X(U32, data_offset) \
X(U32, data_count)
typedef struct Header {
#define X(type, name) type name;
HEADER_FIELDS
#undef X
} Header;
// Generate field offsets
U32 header_offsets[] = {
#define X(type, name) [HeaderField_##name] = offsetof(Header, name),
HEADER_FIELDS
#undef X
};
Switch Generation
#define MESSAGE_TYPES \
X(Connect, connect_handler) \
X(Disconnect, disconnect_handler) \
X(Data, data_handler)
void handle_message(Message *msg)
{
switch (msg->type) {
#define X(type, handler) case MsgType_##type: handler(msg); break;
MESSAGE_TYPES
#undef X
default: unknown_handler(msg); break;
}
}
Named Parameters
C doesn't support named parameters, but compound literals approximate them.
Pattern
typedef struct OpenParams OpenParams;
struct OpenParams
{
String8 path;
B32 read_only;
B32 create_if_missing;
U32 permissions;
};
internal File file_open_(OpenParams *params);
#define file_open(...) file_open_(&(OpenParams){ \
.path = {0}, \
.read_only = 0, \
.create_if_missing = 0, \
.permissions = 0644, \
__VA_ARGS__ \
})
// Usage - only specify what you need
File f = file_open(
.path = str8_lit("data.bin"),
.read_only = 1
);
File f2 = file_open(
.path = str8_lit("output.txt"),
.create_if_missing = 1,
.permissions = 0600
);
Linked List Macros
Generic linked list operations without function pointers.
Singly-Linked List
// Stack push/pop
#define SLLStackPush_N(f, n, next) ((n)->next = (f), (f) = (n))
#define SLLStackPop_N(f, next) ((f) = (f) ? (f)->next : 0)
// Queue push
#define SLLQueuePush_NZ(f, l, n, next, zchk, zset) \
do { \
if (zchk(f)) { (f) = (l) = (n); } \
else { (l)->next = (n); (l) = (n); } \
zset((n)->next); \
} while (0)
// With null termination
#define SLLQueuePush(f, l, n) SLLQueuePush_NZ(f, l, n, next, ((f)==0), ((n)->next=0))
Doubly-Linked List
#define DLLInsert_NPZ(nil, f, l, p, n, next, prev) \
do { \
(n)->next = (p) ? (p)->next : (f); \
(n)->prev = (p); \
if ((n)->next != (nil)) (n)->next->prev = (n); \
else (l) = (n); \
if ((n)->prev != (nil)) (n)->prev->next = (n); \
else (f) = (n); \
} while (0)
#define DLLPushBack(f, l, n) DLLInsert_NPZ(0, f, l, l, n, next, prev)
#define DLLPushFront(f, l, n) DLLInsert_NPZ(0, f, l, 0, n, next, prev)
#define DLLRemove_NPZ(nil, f, l, n, next, prev) \
do { \
if ((n)->next != (nil)) (n)->next->prev = (n)->prev; \
else (l) = (n)->prev; \
if ((n)->prev != (nil)) (n)->prev->next = (n)->next; \
else (f) = (n)->next; \
} while (0)
// Usage
typedef struct Node Node;
struct Node { Node *next; Node *prev; int data; };
Node *first = 0, *last = 0;
Node *n = push_struct(arena, Node);
DLLPushBack(first, last, n);
Type-Generic Macros
Macros that work on any type using sizeof and typeof (GCC/Clang).
Array Count
#define ArrayCount(a) (sizeof(a) / sizeof((a)[0]))
Type-Safe Allocation
#define push_array(arena, T, count) \
(T *)arena_push((arena), sizeof(T) * (count), _Alignof(T), 1)
Generic Swap
#define Swap(a, b) do { \
typeof(a) _tmp = (a); \
(a) = (b); \
(b) = _tmp; \
} while (0)
Containerof
#define containerof(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
// Usage
typedef struct {
Node node;
int value;
} MyNode;
MyNode *owner = containerof(node_ptr, MyNode, node);
Macro Hygiene
Multiple Evaluation
// WRONG: Arguments evaluated multiple times
#define SQUARE(x) ((x) * (x))
int y = SQUARE(i++); // i incremented twice!
// CORRECT: Use statement expression (GCC/Clang)
#define SQUARE(x) ({ \
typeof(x) _x = (x); \
_x * _x; \
})
Operator Precedence
// WRONG: Missing parentheses
#define DOUBLE(x) x + x
int y = DOUBLE(1) * 2; // Expands to 1 + 1 * 2 = 3, not 4
// CORRECT: Always parenthesize
#define DOUBLE(x) ((x) + (x))
Semicolon Handling
// WRONG: Forces semicolon
#define START_BLOCK() {
#define END_BLOCK() }
// CORRECT: do-while(0) swallows semicolon
#define SAFE_BLOCK(stmt) do { stmt; } while (0)
Token Pasting and Stringification
// Paste tokens
#define PASTE(a, b) a ## b
#define PASTE3(a, b, c) a ## b ## c
// Stringify
#define STRINGIFY(x) #x
#define XSTRINGIFY(x) STRINGIFY(x)
// Usage
#define MAKE_VAR(prefix, num) PASTE(prefix, num)
int MAKE_VAR(var, 1) = 10; // int var1 = 10;
#define VERSION 123
const char *version_str = XSTRINGIFY(VERSION); // "123"
Quick Reference
// Defer cleanup
DeferLock(acquire(&lock), release(&lock)) { ... }
MutexScope(mutex) { ... }
// Iterate
for EachIndex(i, count) { process(arr[i]); }
for EachNode(node, list) { ... }
// X-macro
#define LIST X(a) X(b) X(c)
typedef enum { #define X(n) Item_##n, LIST #undef X } Item;
// Named params
File f = file_open(.path = path, .read_only = 1);
// Linked list
SLLQueuePush(first, last, node);
DLLRemove(first, last, node);