C++ Reference ยท Preprocessor, Tools and Concepts
The #define directive and macros
Reference for #define and #undef: object-like and function-like macros, stringizing, token pasting, variadic macros, and the pitfalls that modern C++ avoids.
#define creates a macro: a name that the preprocessor replaces with other text before compilation. A macro knows nothing about types, scopes or namespaces; it is a find-and-replace on tokens. That makes macros powerful (they can generate code, stringify names and depend on the build) and dangerous (they ignore scope and can evaluate arguments more than once).
There are two kinds. An object-like macro (#define LIMIT 100) is a plain replacement. A function-like macro (#define SQUARE(x) ((x) * (x))) takes arguments, which are substituted textually into the replacement. In modern C++ you should prefer constexpr variables, inline functions, templates and enum class; keep macros for what only the preprocessor can do: conditional compilation, include guards, stringizing, __FILE__/__LINE__ capture and token generation.
#define LIMIT 100 #define SQUARE(x) ((x) * (x)) #undef LIMIT // remove the definition
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 std::cin or std::getline), 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 std::cin or std::getline), it gets the next line from this box.
Syntax
#define identifier replacement-list #define identifier(parameters) replacement-list #define identifier(parameters, ...) replacement-list // variadic: __VA_ARGS__, __VA_OPT__(x) #undef identifier
| Piece | Description |
|---|---|
identifier |
The macro name, by convention UPPER_SNAKE_CASE. |
#param |
Stringizing: turns the argument tokens into a string literal. |
a ## b |
Token pasting: joins two tokens into one identifier or number. |
__VA_ARGS__ |
The arguments matched by .... |
__VA_OPT__(text) |
C++20: expands to text only if ... received at least one token. |
#undef |
Removes the definition. It is not an error to undefine a name that is not defined. |
Errors: redefining a macro with a different replacement is ill-formed (compilers warn or error); an identical redefinition is allowed. Calling a function-like macro with the wrong number of arguments is an error.
Usage notes
- Parenthesize everything. Wrap each parameter use and the whole expansion in parentheses, as in
((x) * (x)), or operator precedence will bite you. - Arguments may be evaluated more than once.
SQUARE(i++)increments twice, which is undefined behavior. Use aninlineorconstexprfunction (or a template) when the argument could have side effects. - No scope. A macro defined in a header leaks into every file after it, and it replaces names even inside namespaces, classes and strings of tokens. Give macros unique prefixes (
MYLIB_) and#undeftemporary ones. - Don't name a macro like a common word. A header defining
minormaxas macros (as<windows.h>does withoutNOMINMAX) breaksstd::min. - Prefer
constexprfor constants (constexpr int limit = 100;),enum classfor related constants andinlinefunctions for operations. They respect scope and show up in the debugger and in error messages. - Multi-statement macros should use
do { ... } while (0)so they behave like a single statement after anif. - Command-line definitions:
-DNAMEor-DNAME=valuedefines a macro for the whole build;-UNAMEundefines it. - Stringizing and pasting do not expand their operands first. To expand a macro argument before stringizing it, add one level of indirection (
#define STR(x) STR_(x)and#define STR_(x) #x). - Function-like macros are not found unless followed by
(, so a function pointer named like the macro is not replaced. - Capturing the call site: for
__FILE__and__LINE__, preferstd::source_locationin new code; it needs no macro.