Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 135 ยท Preprocessor

Macros

Learn C function-like macros - parentheses rules, double evaluation pitfalls, # and ##, do-while(0), variadic macros with __VA_OPT__, _Generic and X-macros.

In The Preprocessor you used #define to give names to constants. Macros can also take arguments: #define SQUARE(x) ((x) * (x)) looks like a function, and SQUARE(5) looks like a call. But nothing is called. The preprocessor copies the argument's tokens into the replacement text, and the compiler sees ((5) * (5)).

That copy-and-paste nature gives macros abilities no function has: they work on any type, they can turn code into strings, glue names together, and generate repetitive code. It also gives them traps no function has: operator precedence surprises, arguments evaluated twice, and errors reported in code you never wrote. This lesson teaches the rules that keep macros safe, the tricks experienced C programmers rely on, and when to use an inline function instead.

Function-like macros

A function-like macro has a parameter list right after its name, with no space before the opening parenthesis:

C First function-like macros

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.

The same SQUARE works for int and double, and MAX for numbers and characters, because the macro never sees types: it only pastes tokens. ARRAY_LENGTH is a classic that every C codebase has under some name. It only works on real arrays, never on pointers, as explained in Pointers and Arrays.

If you write a space, #define SQUARE (x) ((x) * (x)), you get an object-like macro named SQUARE whose value is (x) ((x) * (x)). A function-like macro name that isn't followed by ( is left alone, so you can still have a variable or a function with the same name.

Rule 1: parenthesize everything

Since arguments are pasted as tokens, operator precedence can rearrange your expression. Compare a careless macro with a careful one:

C Why the parentheses matter

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.

  • BAD_SQUARE(2 + 3) expands to 2 + 3 * 2 + 3, which is 11, not 25. Parentheses around each parameter fix it.
  • 10 / BAD_DOUBLE(5) expands to 10 / (5) + (5), which is 7, not 1. Parentheses around the whole replacement fix it.

So the rule is: wrap every use of a parameter in parentheses, and wrap the entire expression in parentheses. Exceptions are rare (an argument used as a declaration or string, for instance).

Rule 2: beware of arguments with side effects

A function evaluates each argument exactly once. A macro evaluates it as many times as the parameter appears. If the argument has a side effect, such as ++ or a function call that prints, the effect happens more than once:

C Double evaluation

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.

MAX(i++, 3) becomes ((i++) > (3) ? (i++) : (3)): i is incremented once by the comparison and again in the chosen branch, so m is 6 and i is 7. With the inline function, i++ runs once: m is 5, i is 6. In the second macro call, next_value() runs twice: its first result (10) wins the comparison against 5, but the macro then calls it again and returns 20.

There's no reliable way to stop a caller from passing side effects, so:

  • Name macros in UPPER_CASE so callers know to pass plain values.
  • Prefer a static inline function (see inline Functions) whenever the types are known. It's type-checked, evaluates arguments once, and modern compilers make it just as fast.

GCC and Clang offer a non-standard statement expression that avoids double evaluation, but it isn't portable C, and you'll mostly see it inside the Linux kernel.

Multi-statement macros and do { } while (0)

A macro that expands to several statements has a hidden trap. Look at this one:

C
#define SWAP_BAD(a, b) int tmp = a; a = b; b = tmp;

if (x > y)
    SWAP_BAD(x, y);     /* only "int tmp = x;" belongs to the if! */

Without braces, only the first statement is controlled by the if. Wrapping the statements in { } helps, but then if (...) SWAP(x, y); else ... breaks, because the ; after } ends the if and leaves the else without a partner. The standard idiom is to wrap the body in do { ... } while (0). It's a single statement that runs exactly once and requires a semicolon after it, just like a function call:

C The do-while(0) idiom

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.

Two more details make SWAP safer: the temporary has an unusual name (swap_tmp_) so it can't collide with the caller's variables (a caller variable named tmp would break a macro that declares tmp), and each line ends with a backslash so the macro spans several lines. Our examples omit braces after if here only to show the problem the idiom solves; in your own code, always use braces.

Stringizing with

Inside a function-like macro, #param turns the argument into a string literal of its exact source text. This is how assertion and logging macros print the expression that failed:

C Stringizing arguments

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.

#expr gives "width * height", so the output shows the code and its value side by side. Only the failing CHECK prints.

The last two lines show a famous subtlety. Arguments used with # are not macro-expanded first, so STR(VERSION_MAJOR) produces "VERSION_MAJOR". Going through a second macro, XSTR, expands the argument to 3 before STR stringizes it, giving "3". You need this two-level trick whenever you want to stringize the value of a macro.

Token pasting with

a ## b glues two tokens into one. It lets a macro build identifiers:

C Generating functions with ##

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.

DEFINE_MAX_FUNCTION(int) creates a real function named max_int. This is a simple form of generic programming in C: one macro stamps out a type-specific function for each type. It works only for type names that are single identifiers; for unsigned long you'd first make a typedef. Like #, arguments next to ## aren't expanded before pasting.

Variadic macros

A macro can take a variable number of arguments with ..., and __VA_ARGS__ stands for all of them (C99). C23 adds __VA_OPT__(tokens), which inserts its tokens only when the variable part isn't empty, solving the old problem of a dangling comma:

C Variadic logging macro

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.

In INFO("server started") there are no extra arguments, so __VA_OPT__(,) produces nothing and the call becomes fprintf(stdout, "[%s] " "server started" "\n", "INFO"). With arguments, the comma appears. The format string is joined with the surrounding literals, so it must be a literal. Before C23, code used GCC's , ##__VA_ARGS__ extension for the same purpose; you'll still see it in older projects. To write real functions with variable arguments, see Variadic Functions.

Type-generic macros with _Generic

C11 added _Generic, which picks an expression based on the type of its controlling expression at compile time. Combined with a macro, it gives C a form of overloading. This is how <tgmath.h> makes sqrt(x) call sqrtf, sqrt or sqrtl:

C Overloading with _Generic

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.

Each _Generic has a list of type: expression pairs, and exactly one expression is chosen; the others aren't evaluated. PRINT selects a function and then calls it with (x), so each call is type-checked against the chosen function. Two details show up in the output: a character literal like 'x' has type int in C (not char), and the string literal "text" has type char * after array-to-pointer conversion.

X-macros: one list, many uses

When the same list of items must appear in several places, such as an enum and a matching table of names, an X-macro keeps them in sync. You write the list once as a macro that calls another macro, X, for each item, then define X differently each time you expand the list:

C X-macros for an enum and its names

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.

The list expands three times: into enumerators (COLOR_RED, ...), into strings ("RED", ...) and into values. Add a line to COLOR_LIST and all three stay consistent automatically, the problem Enumerations solved by hand. X-macros look strange at first, but they're common in compilers, emulators and protocol code.

Macros or functions?

Use a macro when you need Use an inline function when
The argument's source text (#) The types are known
To build identifiers (##) Arguments may have side effects
__FILE__/__LINE__ of the caller You want type checking and clear errors
To work on any type, or with _Generic You want to step through it in a debugger
Code generation (X-macros) Anything else

Macros are a sharp tool. Keep them short, uppercase, parenthesized and well commented, and when a function can do the job, use the function.

Type-generic code with _Generic

The PRINT macro earlier is the core idea of _Generic. Building type-generic interfaces you can rely on takes a few more rules: exactly which type the selection sees, how to dispatch on two arguments, and how to turn a wrong type into a compile-time error.

Which type does _Generic see?

The controlling expression is never evaluated; only its type matters. That type is taken after the conversions that happen whenever a value is read (lvalue conversion):

  • Top-level qualifiers are dropped: a const int variable selects int. Qualifiers behind a pointer stay, so &limit is const int *.
  • Arrays become pointers to their first element, and functions become function pointers.
  • The integer promotions are not applied to the expression itself, so a short variable selects short. Arithmetic is a different story: small + 1 is an int.

Two more facts trip people up. char, signed char and unsigned char are three distinct types, while a typedef never creates a new type: int8_t is just another name for signed char here, and size_t is unsigned long. Run this to see the rules in action:

C What type does _Generic see?

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.

A comparison like 1 < 2 has type int in C, not bool; only true, false and bool variables have type bool. C23's nullptr has its own type, nullptr_t, which isn't in the list, so it lands on default.

Because typedefs aren't new types, listing two names for the same type is an error. _Generic((x), int: 1, int32_t: 2) fails with '_Generic' specifies two compatible types on systems where int32_t is int, and it might compile on another system where it isn't. Write associations for the basic types (int, long, long long, ...) and the fixed-width typedefs will match one of them automatically.

If no association matches and there is no default, compilation stops with an error such as '_Generic' selector of type 'float' is not compatible with any association. That's often exactly what you want, as you'll see below.

Dispatching on two arguments

_Generic looks at a single expression, so how do you write a type-generic MAX(a, b)? Use the arithmetic rules: (a) + (b) has the common type of both operands (int and double give double, long and int give long), and _Generic never evaluates it, so the sum costs nothing:

C A type-generic MAX that calls real functions

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.

Compare this with the plain MAX macro from Rule 2: here i++ runs exactly once, because the selected function receives each argument once. Each call is also type-checked against the chosen function, and MAX(2, 2.5) correctly returns a double instead of truncating. If you remove the float line, MAX(1.5f, 1) stops compiling instead of silently choosing the wrong function. For more than two types per argument, you can nest _Generic expressions, but the number of cases grows quickly, so most libraries convert to a common type first, as here.

Compile-time type checks

Since _Generic yields a constant when its branches are constants, it combines with static_assert (C23; _Static_assert in C11) to check types at compile time. Together with C23's typeof, this makes macros that refuse bad arguments:

C static_assert with _Generic and typeof

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.

The two file-level assertions document assumptions the code depends on. Inside SWAP, the assertion compares the types of both arguments. Try adding SWAP(x, d); to main: the build fails with static assertion failed: "SWAP needs two objects of the same type" instead of silently converting 2.5 to 2 and back.

Where you'll meet it, and its limits

The standard library uses _Generic behind <tgmath.h>, where sqrt(x), pow(x, y) and fabs(x) pick the float, double, long double or complex version automatically, and behind C23's <stdbit.h> macros such as stdc_count_ones. In your own code it's ideal for small, closed sets of types: printing helpers, checked conversions and safer macros.

It isn't real overloading, though. The list of types is fixed where the macro is defined, so another header can't add a case for its own struct; each struct type needs its own line; and error messages point into the macro. If you find yourself writing dozens of cases, a void * interface with a size or callback (see void Pointers) is usually the better design. (A note for the future: the next C standard, informally C2y, also lets you write a type name instead of an expression, as in _Generic(int, ...). GCC 15 already accepts it, but don't rely on it in portable code yet.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With #define TRIPLE(x) x * 3, what is TRIPLE(1 + 1)?

    It expands to 1 + 1 * 3, and multiplication goes first: 1 + 3 = 4. Writing ((x) * 3) gives 6.
  2. 2. With #define MAX(a, b) ((a) > (b) ? (a) : (b)), int i = 2; int m = MAX(i++, 0);. What are m and i?

    i++ appears twice in the expansion. The comparison uses 2 and increments i to 3; the chosen branch yields 3 and increments i to 4.
  3. 3. Why are multi-statement macros wrapped in do { ... } while (0)?

    The do-while(0) wrapper is one statement, runs exactly once, and works correctly in every place a function call would.
  4. 4. Given #define N 10, #define STR(x) #x and #define XSTR(x) STR(x), what is XSTR(N)?

    XSTR's argument is expanded to 10 before being passed to STR, which turns it into the string "10". STR(N) alone would give "N".
  5. 5. What does _Generic('a', char: 1, int: 2, default: 3) evaluate to in C?

    In C, a character literal like 'a' has type int, so the int branch is chosen.

Summary

  • A function-like macro (#define NAME(params) ..., no space before () pastes argument tokens into its body.
  • Parenthesize each parameter and the whole replacement to avoid precedence bugs.
  • Arguments are evaluated once per appearance: never pass side effects, and prefer static inline functions when types are known.
  • Wrap multi-statement macros in do { ... } while (0) and end lines with \.
  • #x turns an argument into a string; a ## b pastes tokens. Use a second macro level to expand an argument before stringizing.
  • ... and __VA_ARGS__ make variadic macros; C23's __VA_OPT__ handles empty argument lists.
  • _Generic (C11) selects by type for overloading-style macros; X-macros generate several parallel lists from one.

Next: Conditional Compilation