Example 1 — Small helpers marked inline
Behavior is the same as a normal function.
#include <stdio.h>
static inline int square(int x) { return x * x; }
static inline int max2(int a, int b) { return a > b ? a : b; }
int main(void) {
int i = 3;
printf("square(7) = %d\n", square(7));
printf("max(4, 9) = %d\n", max2(4, 9));
int r = square(i++);
printf("square(i++) = %d, i = %d\n", r, i);
return 0;
} How It Works
static inlinekeeps one private copy per file.- Unlike a macro,
square(i++)evaluatesi++exactly once, so3 * 3 = 9. - Afterwards
iis 4. A macro#define SQUARE(x) ((x)*(x))would increment twice and be undefined.
