Learn C
#include "preprocessor/function_macros.h"

Function-Like Macros in C

#concept

Function-like macros (#define MAX(a,b) ((a) > (b) ? (a) : (b))) stamp expressions inline with zero call overhead and any-type flexibility — the poor man's generics. The price is textual semantics: arguments evaluate every time they appear, so MAX(i++, j++) increments twice, and missing parentheses warp precedence.

The do { ... } while (0) wrapper makes multi-statement macros behave as single statements in if/else chains. Modern guidance: static inline functions first (typed, debuggable, single-evaluation), macros only for what functions can't do (stringification, __LINE__ capture, conditional code).

#how it works
1

Parenthesize everything

#define SQUARE(x) ((x) * (x)) — outer parens plus per-argument parens, or x + 1 style calls expand catastrophically.

2

Arguments may evaluate twice

MAX(i++, 5) increments i twice when i wins — never pass side effects to macros; this is the rule that bites.

3

Wrap multi-statement macros

do { ... } while (0) makes LOG(x); safe inside unbraced if/else — the trailing semicolon parses as one null loop.

4

Functions first

static inline int maxi(int a, int b) does the same job typed and debuggable — reserve macros for generics and context capture.

#example
#include <stdio.h>
 
#define SQUARE(x) ((x) * (x))
 
int main(void) {
printf("%d\n", SQUARE(3 + 1));
return 0;
}
Output
16
1SQUARE(3 + 1) pastes ((3 + 1) * (3 + 1)) — inner parens save it from expanding to 3 + 1 * 3 + 1 = 7.
2The fully-parenthesized expansion evaluates to 16 correctly.
3One output line proves the macro behaved — this time; unparenthesized versions fail exactly here.
#use cases
Type-generic min/max/clamp where functions would need per-type copies
Multi-statement logging and assertion macros wrapped in do-while-0
Auditing macro call sites for side-effect arguments
Replacing macros with static inline functions wherever types suffice

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.