In C++, why replace #define constants and function-like macros with constexpr variables, inline functions or templates?
answer
- text substitution before parsing
- no type, no scope, no namespace
- arguments pasted, so evaluated twice
- inline constexpr since C++17
basics
~20 sMacros are text substitutions done before the compiler parses C++, so they ignore types, scopes and namespaces, can evaluate an argument twice and vanish from debuggers. constexpr variables, inline functions and templates do the same jobs as real, checked entities.
solid answer
~50 sThe preprocessor replaces a macro's name with its tokens before the compiler sees any C++, so a macro has **no type, no scope and no namespace**: `#define MAX_LEVEL 5` rewrites every later `MAX_LEVEL` in the translation unit, including one inside your own namespace or a header you include afterwards. A **function-like macro** pastes its arguments, so `LOG_CLAMP(next_level())` can call `next_level()` twice, and its parameters are never type-checked. The C++ replacements are real entities: `inline constexpr int max_level = 5;` (an inline variable, C++17) or `constexpr` for constants, `enum class` for related constants, and an `inline` or `constexpr` function or a function template instead of a function-like macro. They evaluate each argument once, obey namespaces and overload resolution, show up in debuggers and error messages, and typically cost nothing at run time once optimized. Macros remain for what C++ cannot express: include guards, conditional compilation, stringizing and pasting.
code
cpp · 21 lines#include <algorithm>
#include <cstdio>
#define LOG_MAX_LEVEL 5 // no type, no scope
#define LOG_CLAMP(x) ((x) > LOG_MAX_LEVEL ? LOG_MAX_LEVEL : (x))
namespace logx {
inline constexpr int max_level = 5; // typed, scoped, visible to a debugger
constexpr int clamp(int x) { return std::min(x, max_level); }
} // namespace logx
int reads = 0;
int next_level() { return 4 + ++reads; } // has a side effect
int main() {
int a = LOG_CLAMP(next_level()); // next_level() runs twice
std::printf("macro: %d after %d calls\n", a, reads);
reads = 0;
int b = logx::clamp(next_level()); // argument evaluated once
std::printf("function: %d after %d calls\n", b, reads);
}go deeper
Recall the replacements: constexpr or inline constexpr for constants, enum class for related codes, inline or constexpr functions and templates for function-like macros.
Explain why with mechanics: the preprocessor substitutes text before parsing, so macros ignore namespaces and types and paste arguments that may be evaluated twice.
Show judgment about what remains a macro, such as include guards, conditional compilation, stringizing and location capture, and how to contain the ones you keep with prefixes and undef.
Set a codebase rule that new constants and helpers are language entities, with macros allowed only for source-text jobs and named with a project prefix, and enforce it in review.
## What a macro really is A **macro** is an instruction to the **preprocessor**, which runs before the C++ compiler proper. `#define NAME tokens` tells it to replace every later occurrence of the identifier `NAME` in the translation unit with `tokens`. A **function-like macro**, `#define F(x) ...`, replaces `F(argument)` with its body after pasting the argument's tokens wherever `x` appears. The compiler then parses the result as if you had typed it. That design explains every problem below: the preprocessor knows nothing about types, scopes, namespaces or how many times an expression runs. ## The problems in C++ code - **No scope or namespace.** A macro is active from its `#define` to the end of the translation unit or a matching `#undef`. `#define MAX_LEVEL 5` in a logging header rewrites `MAX_LEVEL` in every file that includes it, even `logx::config::MAX_LEVEL` or an enumerator with that name, often producing baffling syntax errors. - **No type.** `#define TIMEOUT 30` is just the token `30`. It converts silently wherever it lands, and nothing checks that it is used as seconds rather than milliseconds. - **Arguments evaluated more than once.** A function-like macro copies the argument's text, so an argument with a side effect runs as many times as the parameter appears in the body. - **No type checking of parameters.** Any tokens are accepted until the expanded text fails to compile, and the error then points into the expansion. - **Invisible to tools.** After preprocessing the name is gone, so a debugger cannot show `MAX_LEVEL`, and diagnostics mention the expanded text. The double evaluation is easy to demonstrate: ```cpp #define LOG_MAX_LEVEL 5 #define LOG_CLAMP(x) ((x) > LOG_MAX_LEVEL ? LOG_MAX_LEVEL : (x)) int reads = 0; int next_level() { return 4 + ++reads; } int a = LOG_CLAMP(next_level()); // calls next_level() twice: a == 6 ``` The first call returns 5, which is not greater than 5, so the conditional evaluates `(x)` again, calls `next_level()` a second time and returns 6, above the very maximum the macro was meant to enforce. ## The C++ replacements | Macro use | Replacement | What you gain | |---|---|---| | `#define MAX_LEVEL 5` | `inline constexpr int max_level = 5;` (C++17) or `constexpr int max_level = 5;` | type, namespace, usable in constant expressions | | a family of `#define` codes | `enum class Level { trace, debug, info };` | a distinct type, no implicit conversion to `int` | | `#define LOG_CLAMP(x) ...` | `constexpr int clamp(int x) { return std::min(x, max_level); }` | each argument evaluated once, parameters type-checked | | a generic `MAX(a, b)` | `std::max`, or a function template | overload resolution, works with user types | | `#define TAG "net"` | `inline constexpr std::string_view tag = "net";` (C++17) | a typed, sized constant | Some notes on these: 1. A namespace-scope `constexpr` variable is implicitly `const`, which gives it internal linkage, so each translation unit gets its own copy; `inline` (C++17) makes it one entity across the program. The material on linkage covers why that matters. 2. `inline` on a function lets its definition live in a header without multiple-definition errors; it is at most a hint about inlining, which compilers decide on their own. 3. These replacements typically cost nothing at run time once optimized. A `constexpr` function called with constant arguments in a constant expression is evaluated at compile time. ## What still needs the preprocessor C++ has not replaced every macro job, and an honest answer says so: - **Include guards** (or `#pragma once`) for headers. - **Conditional compilation** with `#if`, `#ifdef` and `__has_include` for platform and feature differences. - **Stringizing** `#x` and **token pasting** `a##b`, for example to print the text of a failed assertion. - Capturing the caller's location in pre-C++20 code with `__FILE__` and `__LINE__`; C++20's `std::source_location` covers most of that now. The interview summary: macros are text, so they bypass every rule the language gives you. Use `constexpr`, `inline`, `enum class` and templates for values and functions, and keep macros for the few jobs that are genuinely about the source text.
- Why write inline constexpr for a constant in a header instead of plain constexpr?A namespace-scope constexpr variable is const, so it has internal linkage and every translation unit that includes the header gets its own copy, with its own address. inline constexpr, available since C++17, makes it a single entity shared by the whole program, which matters when its address is taken or it is a larger object.
- Which jobs can a constexpr function or template not take over from a macro?Anything that works on source text rather than values: include guards, choosing code with #if before it is compiled, turning an expression into a string with #, pasting identifiers with ##, and, before C++20, capturing the caller's __FILE__ and __LINE__. Those stay macros; values and computations move to the language.
- A #define constant is scoped to the namespace it is written in
- Function-like macros are faster than inline functions because there is no call
- A macro argument is evaluated once, like a function argument
- inline on a function forces the compiler to inline it
- constexpr variables always cost a memory load at run time