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
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.