C Reference ยท Functions and Scope
Macros vs. functions
Compare function-like macros and functions in C: type safety, double evaluation, debugging, speed and the cases where only a macro will work.
A function-like macro and a function can look identical at the call site, but they work differently. A function is compiled once, has typed parameters, evaluates each argument exactly once and can be stepped through in a debugger. A macro is text substitution done before compilation: it has no types, may evaluate an argument several times and leaves no trace for the debugger.
Modern C compilers inline small functions on their own, so the old "macros are faster" argument rarely holds. Prefer a function (optionally static inline) unless you need something only the preprocessor can do.
#define SQUARE_M(x) ((x) * (x)) static inline int square_f(int x) { return x * x; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
This page compares two constructs rather than defining one.
| Question | Function | Macro |
|---|---|---|
| Argument types checked? | Yes, with implicit conversion | No |
| Argument evaluated | Once | Zero, one or many times |
| Works on any type? | Only the declared one (use _Generic or one function per type) |
Yes |
| Can take its address? | Yes | No |
| Can recurse? | Yes | No |
Sees #, ##, __FILE__, __LINE__ of the caller? |
No | Yes |
| Debugger / stack trace | Visible | Expanded in place |
| Error messages | Point at the call | Point into the expansion |
Usage notes
- Use a function by default. Make small helpers
static inlinein a header so the compiler can inline them. Seeinline. - Use a macro when you must work with source text: stringify an expression (
#expr), paste identifiers (##), capture__FILE__and__LINE__, or write a type-generic helper such asSWAPorARRAY_LEN. - Parenthesize every parameter and the whole body, or precedence will bite.
#define SQ(x) x * xturnsSQ(a + 1)intoa + 1 * a + 1. - Never pass expressions with side effects to a macro that uses its parameter twice (
MAX(i++, j)). If you need the value twice, copy it into a local inside ado { } while (0)block or a GNU statement expression where available. - Wrap multi-statement macros in
do { ... } while (0)so they work in an unbracedifand need a trailing semicolon. - Typed alternatives:
_Genericselects a function by argument type, giving you macro syntax with function safety. See_Generic. - Compile-time constants: in C23 prefer
constexprorenumover#definefor typed constants.