Inline functions and macros
The preprocessor, macro pitfalls, inline functions and X-macros.
The preprocessor is a text editor
Before the compiler sees a file, the preprocessor runs over it: it pastes in #included files, removes #if'd-out code and replaces macros. It knows nothing about types, scope or precedence. That is the source of both the power and every pitfall.
| Directive | Use |
|---|---|
#include | Paste another file in |
#define / #undef | Define or remove a macro |
#if, #ifdef, #elif, #else, #endif | Conditional compilation |
#error, #warning | Stop or warn during the build |
#pragma | Compiler-specific instructions |
# and ## inside a macro | Turn an argument into a string, or paste two tokens together |
Macro pitfalls
Precedence
#include <stdio.h>
#define SQUARE_BAD(x) x * x
#define SQUARE(x) ((x) * (x))
int main(void) {
printf("SQUARE_BAD(1 + 2) = %d\n", SQUARE_BAD(1 + 2)); // 1 + 2 * 1 + 2
printf("SQUARE(1 + 2) = %d\n", SQUARE(1 + 2));
return 0;
}
Rule: parenthesise every use of every argument, and the whole expansion.
Double evaluation
SQUARE(i++) expands to ((i++) * (i++)), which increments twice and is undefined behaviour. MAX(read_adc(), limit) reads the ADC twice. An argument with side effects must never be passed to a macro that uses it more than once. An inline function has neither problem.
Multi-statement macros
#define LED_PULSE() led_on(); delay_ms(10); led_off()
if (error) LED_PULSE(); // only led_on() is inside the if
Wrap statement macros in do { ... } while (0). It behaves as a single statement, requires a semicolon after it, and works under an unbraced if:
#define LED_PULSE() do { led_on(); delay_ms(10); led_off(); } while (0)
Inline functions instead
static inline functions give the speed of a macro with real semantics: arguments evaluated once, type checking, a debugger can step into them.
static inline uint32_t clamp_u32(uint32_t v, uint32_t lo, uint32_t hi) {
return v < lo ? lo : (v > hi ? hi : v);
}
inline is a hint. At -O0 the compiler may not inline; at -Os it may decline if inlining makes the code bigger. Use __attribute__((always_inline)) when it truly matters (in a cycle-counted ISR), and check the disassembly.
Put static inline functions in headers. static gives each file its own copy if the compiler chooses not to inline, which avoids linker errors.
When a macro is still the right tool
- Constants that must work in
#ifand in array sizes in C (C has noconstexprbefore C23). - Register addresses:
#define GPIOA ((gpio_t *)0x40020000u). - Stringifying and pasting tokens, which functions cannot do.
- Conditional compilation for different boards.
- Capturing
__FILE__and__LINE__at the call site in an assert or log macro.
Stringify and paste
#include <stdio.h>
#define STR(x) #x
#define SHOW(expr) printf("%s = %d\n", #expr, (expr))
#define REG(name, n) name##n
int main(void) {
int REG(ch, 0) = 10, REG(ch, 1) = 20; // declares ch0 and ch1
SHOW(ch0 + ch1);
SHOW(ch1 / 3);
printf("%s\n", STR(built from a macro));
return 0;
}
X-macros: one list, many uses
An X-macro keeps a list in one place and expands it several ways. Adding an entry updates the enum, the name table and anything else together, so they can never drift apart.
#include <stdio.h>
#define ERROR_LIST(X) \
X(ERR_NONE, "no error") \
X(ERR_TIMEOUT, "timed out") \
X(ERR_CRC, "bad CRC") \
X(ERR_RANGE, "out of range")
#define AS_ENUM(name, text) name,
#define AS_TEXT(name, text) text,
typedef enum { ERROR_LIST(AS_ENUM) ERR_COUNT } error_t;
static const char *const error_text[] = { ERROR_LIST(AS_TEXT) };
int main(void) {
printf("%d errors defined\n", ERR_COUNT);
for (int e = 0; e < ERR_COUNT; e++) printf("%d: %s\n", e, error_text[e]);
return 0;
}
Common uses: error codes and their strings, register tables for a debug dump, command tables, and state lists for a state machine.
Conditional compilation without the mess
#if defined(BOARD_REV_B)
# define LED_PIN 7
#elif defined(BOARD_REV_A)
# define LED_PIN 5
#else
# error "Define BOARD_REV_A or BOARD_REV_B"
#endif
The #error branch turns a missing definition into a build failure instead of a silently wrong pin. Keep board differences in one header rather than scattering #ifdef through drivers.
Note: MISRA C discourages function-like macros where a function would do (Directive 4.9), forbids
#undefin most cases, and requires macro parameters to be parenthesised (Rule 20.7). Following those rules by habit avoids most macro bugs.
Interview question: Macro or inline function: how do you decide?
Answer: Default to static inline functions: they evaluate arguments once, are type-checked, respect scope and can be debugged, and they inline just as well with optimisation on. Use a macro only for what functions cannot do: compile-time constants needed in #if or array sizes, conditional compilation, stringifying or token pasting, capturing __FILE__ and __LINE__ at the call site, and generic code in C before _Generic.
Interview question: What is an X-macro and why use one?
Answer: A list defined once as a macro that takes another macro as a parameter, for example ERROR_LIST(X) containing X(name, text) entries. Expanding it with different definitions of X generates the enum, the string table, a switch or a register dump from the same list, so adding an entry updates all of them and they cannot get out of step.
Build it: helper macros that cannot bite
This is step 2 of the module project. The lamp's code is full of register fields, so the team wants short helpers. Macros are tempting, but a careless one evaluates its argument twice, or breaks when given an expression. Write the helpers so they are safe however they are called.
Lab: Safe macros and inline functions
Write, below the provided code:
- the macro
BIT(n): a mask with bitnset, as an unsigned value (1u), safe for an expression such asBIT(a + 1); - the macro
FIELD_GET(reg, mask, shift): the field's value,((reg) >> (shift)) & (mask), with every argument in parentheses; - the macro
FIELD_SET(reg, mask, shift, val):regwith that field replaced byval(an expression that returns the new value; it does not assign); static inlinefunctionclamp_u8(int v):vlimited to 0 to 255. It must be a function, not a macro: the tests call it with an argument that has a side effect, and it must be evaluated once.
Going deeper
Interview question: Would you use macros or inline functions for a motor driver's fast pin operations, and why?
Answer: Inline functions: they are as fast once optimised, type-checked, evaluate their arguments once, and can be debugged. Keep macros for what only the preprocessor can do: compile-time constants that must be usable in other macros, conditional compilation, and token pasting. Check the generated code to confirm the inlining happened.
Interview question: What is _Generic in C11 and when is it useful?
Answer: _Generic selects an expression based on the type of its controlling expression at compile time, for example mapping a print macro to different functions for int, float or pointer arguments. It gives C a form of type-based overloading for macros, as used in tgmath.h. It is useful for type-safe generic interfaces without C++, though overuse makes code hard to read.
Interview question: Why do assert and logging macros remain macros even in modern code?
Answer: They need __FILE__, __LINE__ and sometimes __func__ at the call site, which a function cannot obtain, and they often stringify the failing expression with # so the message shows the code. They can also be compiled out completely in release builds. Keep the macro thin: capture the location and call a real function to do the work.
Explain it: In your own words, explain why #define SQUARE(x) x * x gives the wrong answer for SQUARE(1 + 2).
Answer: The preprocessor substitutes text without understanding expressions, so SQUARE(1 + 2) becomes 1 + 2 * 1 + 2, and because multiplication binds tighter than addition that evaluates to 5, not 9. Wrapping each use of the parameter and the whole expansion in parentheses, ((x) * (x)), fixes the precedence, but an argument with side effects such as i++ would still be evaluated twice, so an inline function is the better tool.