skip to content

Macros and Feature Tests

Macros substitute text before the compiler sees it, so C++ code replaces most of them with constexpr, inline and templates. Interviewers ask about include-order bugs and feature-test macros.

on this pageshow

explore

questions

5

In C++, why replace #define constants and function-like macros with constexpr variables, inline functions or templates?

level: juniorimportance: must knowfreq 58%

answer

  1. text substitution before parsing
  2. no type, no scope, no namespace
  3. arguments pasted, so evaluated twice
  4. inline constexpr since C++17

basics

~20 s

Macros 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 s

The 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
cpp
#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

for a junior

Recall the replacements: constexpr or inline constexpr for constants, enum class for related codes, inline or constexpr functions and templates for function-like macros.

for a middle

Explain why with mechanics: the preprocessor substitutes text before parsing, so macros ignore namespaces and types and paste arguments that may be evaluated twice.

for a senior

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.

for a principal

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
open as a page

In a C++ build, why do #if LOGX_TRACE and #ifdef LOGX_TRACE disagree for -DLOGX_TRACE=0 and for a misspelled macro name?

level: middleimportance: should knowfreq 35%

basics

~20 s

#ifdef asks only whether the macro is defined, so -DLOGX_TRACE=0 counts as on. #if evaluates an expression in which every identifier that is not a macro becomes 0, so 0, a missing macro and a misspelled name all silently count as off.

open as a page

Why does std::min(a, b) in a C++ logging header stop compiling when <windows.h> is included before it, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~20 s

<windows.h> defines function-like macros named min and max unless NOMINMAX is defined first. The preprocessor expands min( even after std::, so the compiler sees std:: followed by an expression. Define NOMINMAX project-wide, or write (std::min)(a, b).

open as a page

Before using std::expected in a C++ header built as both C++17 and C++23, why test __cpp_lib_expected rather than __has_include(<expected>) or __cplusplus?

level: seniorimportance: should knowfreq 38%

basics

~20 s

__has_include only says a header file exists; libc++ ships <expected> in every mode but declares nothing before C++23. __cplusplus names the language mode, not what the library implements. __cpp_lib_expected, from <version> or <expected>, says std::expected is usable.

open as a page

In a C++20 logging library, which jobs of a LOG macro can std::source_location take over, and which still need the preprocessor?

level: seniorimportance: should knowfreq 33%

basics

~20 s

std::source_location::current() as a defaulted parameter captures the caller's file, line and function, replacing FILE and LINE. A macro is still needed to stringize an expression, to skip evaluating message arguments when a level is off, and to compile calls out entirely.

open as a page