What is the difference between a macro and an inline function?
Short answer: A macro is text substitution by the preprocessor: no type checking, arguments may be evaluated several times, and it is hard to debug. A static inline function is a real function that the compiler may expand in place: arguments are type-checked and evaluated exactly once, and it can be stepped through in a debugger. Prefer static inline; use macros only for what functions cannot do.
| Macro | static inline function |
|
|---|---|---|
| Processed by | preprocessor | compiler |
| Type checking | none | full |
| Argument evaluation | as many times as it appears | exactly once |
| Scope | ignores scope | normal C scope |
| Debugging | hard (expanded text) | normal (can set breakpoints when not inlined) |
| Generic over types | yes | no (except via _Generic) |
Can use #, ##, __FILE__, __LINE__ of the caller |
yes | no |
| Can return a value from a statement block | only with GCC statement expressions | yes |
The classic macro bugs
#define SQUARE(x) ((x) * (x))
int y = SQUARE(i++); /* i incremented twice: undefined behaviour */
int z = SQUARE(read_adc()); /* the ADC is read twice, maybe giving different values */
#define MAX(a, b) ((a) > (b) ? (a) : (b))
MAX(x++, y) /* x may be incremented twice */
static inline int square(int x) { return x * x; } /* no surprises */
inline is only a hint. The compiler decides whether to inline based on size and optimisation level; __attribute__((always_inline)) forces it. A plain inline (without static) in C has awkward linkage rules (you need one external definition somewhere), which is why static inline in headers is the common idiom.
When macros are the right tool: compile-time constants used in #if, stringification (#define STR(x) #x) and token pasting, logging with the caller's __FILE__/__LINE__, offsetof/container_of-style tricks, and type-generic helpers (with _Generic, or C23 typeof).
Code size: inlining a large function at many call sites increases flash use; on small MCUs, check the map file and use -Os.