Function-Like Macros in C
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).
Parenthesize everything
#define SQUARE(x) ((x) * (x)) — outer parens plus per-argument parens, or x + 1 style calls expand catastrophically.
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.
Wrap multi-statement macros
do { ... } while (0) makes LOG(x); safe inside unbraced if/else — the trailing semicolon parses as one null loop.
Functions first
static inline int maxi(int a, int b) does the same job typed and debuggable — reserve macros for generics and context capture.
#include <stdio.h> #define SQUARE(x) ((x) * (x)) int main(void) { printf("%d\n", SQUARE(3 + 1)); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.