Macros vs Functions in C
Both macros and functions let you reuse code — but they work very differently and each has strengths and weaknesses.Side-by-Side Comparison
| Feature | Macro (#define) | Function |
|---|---|---|
| Processed by | Preprocessor | Compiler |
| Type checking | None | Full |
| Speed | Faster — inlined | Slight call overhead |
| Code size | Larger | Smaller |
| Debugging | Hard — no name in binary | Easy — shows in stack trace |
| Side effects | Args may run multiple times | Args run once |
| Scope | File-wide | Normal C scope rules |
| Recursion | Not possible | Yes |
| Return value | An expression | return statement |
The Side Effect Problem
A macro evaluates its argument expression every time it appears in the expansion:Example: Same Task, Two Ways
As a macro:When to Use Each
Use a macro when:- You need a simple constant (
#define PI 3.14159) - You want to work on any type without templates (
MAX(a, b)) - You need compile-time conditional code (
#ifdef DEBUG) - You need include guards (
#ifndef HEADER_H)
- The logic is complex or more than one line
- You need type safety
- The argument might have side effects
- You need recursion
- Debugging matters
inline Functions (C99+)
C99 introduced inline functions — they give you function-level safety and macro-level speed:
inline functions are preferred over functional macros.