ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 51

Macros vs Inline Functions

Fast code without hidden traps.

A macro is text substitution done before compiling. It costs no call time, but arguments may be evaluated twice and there is no type checking. Wrap every argument and the whole expression in brackets.

An inline function gives the same speed with type checking and safe single evaluation, so prefer it. In C++, constexpr functions go further.

Use macros mainly for constants, bit masks and conditional compilation.

EXAMPLE
#define SQUARE_BAD(x)  x * x            /* SQUARE_BAD(1+2) gives 5! */
#define SQUARE(x)      ((x) * (x))       /* but SQUARE(i++) misbehaves */

static inline int square(int x) { return x * x; }  /* safest */