A function instead of a macro
#define square_macro(X) (X*X) // Avoid this for ordinary squaring. inline unsigned square_unsigned(unsigned x) { return x*x; } If count() increments a counter, square_macro(count()) expands to count()*count() and calls it twice. square_unsigned(count()) calls it once. The inline function also gives the operation a typed function interface. section 17.0
The inline specifier permits, but does not require, a compiler to substitute a function’s body at a call site. When the definition is available, inlining can remove call overhead and expose dead branches or repeated computations to further optimization. A declaration alone does not give a traditional compiler the body it needs. section 16.1
For a small function needed by several translation units:
- Put its inline definition in a header so each translation unit that includes it can see the body. section 16.1
- Use the illustrated external declaration in exactly one translation unit when an external instance is needed. The parameter name can be omitted there to avoid unintended preprocessor replacement. section 16.1
- Check names in header definitions carefully: parameter and local-variable names are visible to the preprocessor. section 16.1
// Inline definition in a header file.
// Function argument names and local variables are visible
// to the preprocessor and must be handled with care.
inline
toto* toto_init(toto* toto_x){
if (toto_x) {
*toto_x = (toto){ };
}
return toto_x;
}
This header definition shows where inline is written and why names inside the definition need preprocessor-aware review. section 16.1
#include "toto.h" // Instantiate in exactly one TU. // The parameter name is omitted to avoid macro replacement. toto* toto_init(toto*);
This companion listing shows the declaration placed in exactly one translation unit. section 16.1
TAKEAWAY: Prefer an inline function to a function-like macro when the number and types of arguments are known. Use inline as a possible optimization for small, pure functions—not as a reason to sacrifice correctness or assume a speedup. Measure performance claims. section 17.0 section 16.5



