Macros
A macro is a named piece of text that the preprocessor substitutes wherever the name appears. Object-like macros stand for a constant or snippet; function-like macros take arguments and paste them into the replacement text.
Detailed Explanation
There are exactly two kinds. An object-like macro is #define MAX_USERS 64: the identifier is replaced by the token sequence after it. A function-like macro has a parameter list with no space before the opening parenthesis, #define SQUARE(x) ((x) * (x)), and at each use the argument text is pasted into the body wherever the parameter appears.
The critical word is text. A macro is not a function. There is no call, no parameter of a declared type, no single evaluation of the arguments, and no return value. Everything awkward about macros comes from that.
Parenthesize the parameters, and parenthesize the whole body. Write #define DOUBLE(x) x * 2 and DOUBLE(1 + 2) expands to 1 + 2 * 2, which is 5. Write #define HALF(x) (x) / 2 and 4 / HALF(4) expands to 4 / (4) / 2, which is 0 rather than 2. The rule is mechanical: wrap every use of a parameter in parentheses, then wrap the entire replacement text in one more pair. This is not style, it is the only way to make the expansion bind the way a reader expects.
Do not mention a parameter twice unless you can accept the argument's expression running twice. The classic offender is #define MAX(a, b) ((a) > (b) ? (a) : (b)), which names both parameters twice. Call it as MAX(x++, y) and x++ appears twice in the expansion, so x may be incremented twice. Call it as MAX(expensive_lookup(k), 0) and the lookup happens twice. A real function cannot behave this way, because arguments are evaluated once before the call.
Multi-statement macros need care. A body of two statements dropped into an unbraced if will attach only its first statement to the if. The traditional fix is do { ... } while (0), which makes the body one statement that still needs a trailing semicolon at the call site.
Two operators exist only inside macros. #param stringifies: it turns the argument text into a string literal, which is how a check macro can print the expression that failed. a ## b pastes two tokens into one identifier, which is how generic-ish code builds names like vec_int_push. Both are hard to read and worth using only when nothing else will do. Stringifying a macro argument that is itself a macro requires the two-level indirection trick, because # suppresses expansion of its operand.
When should you still use a macro today? When you need something the language cannot express:
- capturing the caller's
__FILE__and__LINE__, as assertion and logging macros do - stringifying or token-pasting
- type-generic code, such as an array-length macro that works for any element type
- conditional compilation and header guards
For everything else the modern answer is real C. enum { MAX_USERS = 64 }; or static const size_t MAX_USERS = 64; gives you a typed constant that respects scope and shows up in a debugger. A static inline function in a header (C99) gives you the speed of a macro with argument evaluation exactly once, type checking, and no parenthesization traps. The cost of a macro is not run time; it is that the compiler and debugger see only the expansion, so mistakes are reported in text you did not write.
Code Examples
#include <stdio.h>
/* Parenthesize each parameter AND the whole body. */
#define SQUARE(x) ((x) * (x))
/* Broken on purpose, to show what the rule prevents. */
#define BAD_SQUARE(x) x * x
/* Works for any array type, and only a macro can do it.
Note: this is wrong if passed a pointer, which is why it is
usually paired with a compile-time check in real code. */
#define ARRAY_LEN(a) (sizeof (a) / sizeof (a)[0])
/* do/while(0) makes a multi-statement body behave as one statement. */
#define SWAP_INT(a, b) do { int tmp_ = (a); (a) = (b); (b) = tmp_; } while (0)
int main(void)
{
printf("%d\n", SQUARE(1 + 2)); /* ((1+2)*(1+2)) -> prints: 9 */
printf("%d\n", BAD_SQUARE(1 + 2)); /* 1 + 2*1 + 2 -> prints: 5 */
int scores[] = {90, 75, 60, 88};
printf("%zu\n", ARRAY_LEN(scores)); /* prints: 4 */
int a = 1, b = 2;
if (a < b)
SWAP_INT(a, b); /* one statement, so no braces needed */
printf("%d %d\n", a, b); /* prints: 2 1 */
return 0;
}#include <stdio.h>
/* Double evaluation: the argument text appears twice in the body. */
#define MAX_MACRO(a, b) ((a) > (b) ? (a) : (b))
/* The same job as a function: arguments are evaluated exactly once,
types are checked, and the debugger can step into it. C99 or later. */
static inline int max_int(int a, int b)
{
return a > b ? a : b;
}
int main(void)
{
int i = 5;
printf("%d\n", MAX_MACRO(i++, 3)); /* i++ expands twice: undefined behavior */
int j = 5;
printf("%d\n", max_int(j++, 3)); /* prints 5, and j becomes 6 exactly once */
return 0;
}#include <stdio.h>
/* # stringifies its operand; ## pastes two tokens into one identifier. */
#define STRINGIFY_RAW(x) #x
#define STRINGIFY(x) STRINGIFY_RAW(x) /* extra level expands x first */
#define CHECK(expr) \
do { \
if (!(expr)) \
fprintf(stderr, "check failed: %s at %s:%d\n", \
#expr, __FILE__, __LINE__); /* #expr prints the source text */ \
} while (0)
#define VERSION 11
#define MAKE_NAME(prefix, suffix) prefix ## _ ## suffix
int MAKE_NAME(buffer, size) = 256; /* declares: int buffer_size = 256; */
int main(void)
{
printf("%s\n", STRINGIFY_RAW(VERSION)); /* prints: VERSION */
printf("%s\n", STRINGIFY(VERSION)); /* prints: 11 */
printf("%d\n", buffer_size); /* prints: 256 */
int balance = -5;
CHECK(balance >= 0); /* prints: check failed: balance >= 0 at ...:NN */
return 0;
}Common Gotchas
A macro that uses a parameter twice can evaluate the caller's expression twice
`MAX(i++, 3)` modifies `i` twice with no sequence point between the reads and writes, which is undefined behavior, and `MAX(read_sensor(), 0)` reads the sensor twice. Use a `static inline` function whenever the arguments might have side effects.
Missing parentheses change the meaning of the expansion
`#define HALF(x) (x) / 2` turns `4 / HALF(4)` into `4 / (4) / 2`. Parenthesize every parameter and then the entire body.
A trailing semicolon or a stray space breaks a macro definition
`#define MAX_USERS 64;` injects the semicolon into every use, and `#define F (x) ((x)*2)` defines an object-like macro whose text begins with `(x)` because of the space before the parenthesis.
Macros are invisible to the debugger and to the compiler's error messages
diagnostics point at the expansion, not at your source. `cc -E` shows the text the compiler actually received, which is usually the fastest way to see what went wrong.