A macro and an inline function can both stand in for a small piece of code, but they work in different ways. A macro is text that the preprocessor substitutes before the compiler runs. An inline function is a real function that the compiler type-checks, and the compiler decides whether to expand its body at each call site.
How a macro works
#define SQUARE(x) x * x
int main(void) {
int result = SQUARE(1 + 2); /* expands to 1 + 2 * 1 + 2 */
return result;
}
The preprocessor pastes the text in without adding parentheses, so SQUARE(1 + 2) becomes 1 + 2 * 1 + 2. That evaluates to 5, not 9. The fix is to parenthesize the parameter and the whole expression:
#define SQUARE(x) ((x) * (x))
A macro can also evaluate its argument more than once:
#define TWICE(x) ((x) + (x))
int main(void) {
int value = TWICE(next_number()); /* next_number() is called twice */
return value;
}
If next_number() has side effects, such as incrementing a counter, the second call changes the result.
How an inline function works
inline int square(int x) {
return x * x;
}
int main() {
int result = square(1 + 2); // 9
return result;
}
The argument 1 + 2 is computed once and passed in as a value, so the result is 9. The compiler also checks the argument’s type. Calling square("hello") is a compile error that names the function and its parameter type. The same mistake with a macro shows up only in the expanded code, which can be harder to read.
Side by side
Macro (#define) |
Inline function | |
|---|---|---|
| What it is | Text that the preprocessor replaces | A real function that the compiler knows about |
| Type checking | None | Arguments are checked against the parameters |
| Argument evaluation | Pasted as text, so an argument can run more than once | Evaluated once, before the call |
| Scope | Ignores scope and namespaces | Follows normal scope rules |
| Errors | Point at the expanded code | Point at the call and its parameters |
| Address | Has no address | Can have its address taken |
| Expansion | Always replaced | The compiler decides |
When a macro is still the right tool
Some jobs need the preprocessor, and a function cannot do them:
- Turning a parameter into a string with
#:
#define NAME_OF(x) #x
const char *text = NAME_OF(total); /* "total" */
- Joining tokens together with
##. - Choosing which code to compile with
#ifand#ifdef. - Logging helpers that capture
__FILE__and__LINE__. The macro expands at the place where it is called, so these values describe the caller’s location.
Which one to choose in C++
For most code, prefer an inline function, or a constexpr function when the value is known at compile time. You get type checking, arguments that are evaluated once, and clearer error messages. Save macros for the jobs listed above.
For how inline behaves when a function is defined in a header, see the guide to the inline keyword in C++.