In a C++ build, why do #if LOGX_TRACE and #ifdef LOGX_TRACE disagree for -DLOGX_TRACE=0 and for a misspelled macro name?
answer
- defined versus nonzero
- unknown identifiers become 0
- a typo is silently false
- -Wundef is not in -Wall
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.
solid answer
~50 s`#ifdef LOGX_TRACE` (and `#if defined(LOGX_TRACE)`) tests **whether the name is defined as a macro**, whatever its value, so `-DLOGX_TRACE=0` turns tracing **on**. `#if LOGX_TRACE` evaluates a **constant expression** after macro replacement, and the standard replaces every remaining identifier except `true` and `false` with `0`. So `-DLOGX_TRACE=0`, no definition at all, and the typo `#if LOGX_TRACNG` all evaluate to 0, silently. A bare `-DLOGX_TRACE` defines it as 1, while `#define LOGX_TRACE` with no value makes `#if LOGX_TRACE` an error, `expected value in expression`. Pick one convention per macro: either defined/undefined with `#ifdef`, or always defined to 0 or 1 with `#if`, and turn on `-Wundef`, which neither GCC nor clang enables in `-Wall` or `-Wextra`, to catch undefined names in `#if`. C++17's `if constexpr` cannot replace these when a branch names something that does not exist on the other platform.
code
cpp · 14 lines#include <cstdio>
// Built with -DLOGX_TRACE=0 to turn tracing off, or without it.
int main() {
#ifdef LOGX_TRACE
std::puts("ifdef: trace on"); // also runs for -DLOGX_TRACE=0
#endif
#if LOGX_TRACE
std::puts("if: trace on"); // an undefined name evaluates to 0
#endif
#if LOGX_TRACNG // typo: silently 0
std::puts("never printed");
#endif
}go deeper
Recall that #ifdef checks whether a macro is defined, while #if checks its value.
Explain the rule that remaining identifiers in #if become 0, and walk through -DNAME, -DNAME=0, an empty definition and a typo.
Show how you keep configuration macros safe: one convention per macro, prefixed names, -Wundef in the warning set, and when if constexpr can take over.
Decide a codebase's configuration-macro convention and where defaults live, so build variants cannot silently select the wrong branch.
## Two different questions The preprocessor offers two families of conditional directives, and they ask different questions: - `#ifdef NAME`, `#ifndef NAME`, `defined(NAME)` and C++23's `#elifdef` and `#elifndef` ask **is `NAME` currently defined as a macro?** The value is irrelevant; a macro defined as `0`, or as nothing at all, counts as defined. - `#if expression` and `#elif expression` ask **is this integral constant expression nonzero?** The preprocessor first expands macros in it, then, as the standard says, replaces all remaining identifiers except `true` and `false` with the number `0`. The second rule is the trap. An identifier that is not a macro does not cause an error in `#if`; it quietly becomes `0`. ## What each build actually does | Build | `#ifdef LOGX_TRACE` | `#if LOGX_TRACE` | `#if LOGX_TRACNG` (typo) | |---|---|---|---| | no definition | false | false (0) | false (0) | | `-DLOGX_TRACE` | true | true (defined as 1) | false | | `-DLOGX_TRACE=0` | **true** | false | false | | `-DLOGX_TRACE=1` | true | true | false | | `#define LOGX_TRACE` (empty) | true | error: `expected value in expression` | false | The `-D` rows follow from the driver rule that `-D name` alone predefines `name` as `1`, documented for GCC and matched by clang. The empty-definition row is clang's actual diagnostic: after replacement, `#if` has nothing to evaluate. The misspelled column is the one that bites: a typo in a `#if` that guards debug-only checks or a platform branch compiles cleanly and silently selects the other branch. ## What a #if expression can see The preprocessor runs before the compiler knows anything about C++ declarations, so a `#if` expression can use only integer literals, macros, arithmetic, comparisons, logical operators, `defined`, `__has_include` and `__has_cpp_attribute`. Everything the language declares is invisible to it: - `constexpr int log_level = 2;` followed by `#if log_level > 1` takes the **else** branch, because `log_level` is not a macro and becomes `0`. Clang even warns that the variable is unused, since nothing the compiler parsed refers to it. - `sizeof`, casts, enumerators and `constexpr` functions are not available; GCC's manual notes that `sizeof` is not recognized in `#if`. A condition that depends on a type or a `constexpr` value belongs in `static_assert` or `if constexpr`, not in `#if`. ## Making the convention safe 1. **Pick one style per macro and document it.** Either the macro is present or absent and is tested with `#ifdef`, or it is always defined to `0` or `1` (with a default in a config header) and tested with `#if`. 2. **Turn on `-Wundef`.** It warns about an identifier in `#if` that is not a macro; clang's text is `'LOGX_TRACNG' is not defined, evaluates to 0`. GCC's option table leaves it off by default, and neither compiler's `-Wall` or `-Wextra` enables it, so it has to be named. The material on warnings covers warning sets. 3. **Combine tests when a value matters**: `#if defined(LOGX_LEVEL) && LOGX_LEVEL >= 2` reads clearly and survives both styles. 4. **Prefix project macros** (`LOGX_`) so they cannot collide with platform or library macros. ## Where if constexpr fits, and where it does not C++17's `if constexpr (condition)` discards the branch that is not taken, and inside a template a discarded branch is not instantiated. That makes it a good replacement for `#if` when **both branches are valid C++ on every platform**, for example choosing between two algorithms based on `sizeof(void*)`. It cannot replace the preprocessor when one branch refers to something that does not exist in this build: ```cpp constexpr bool on_windows = false; void flush_debug() { if constexpr (on_windows) { OutputDebugStringA("x"); // error: use of undeclared identifier } } ``` The discarded branch is still parsed, and names in it that do not depend on a template parameter must still be declared, even inside a template; clang rejects both cases with `use of undeclared identifier 'OutputDebugStringA'`. Platform APIs, platform headers and code that only compiles under one toolchain therefore stay behind `#if` or `#ifdef`, while choices between valid alternatives can move to `if constexpr`. ## Interview summary - `#ifdef` tests definition, `#if` tests value, and an undefined identifier in `#if` is `0`. - `-DNAME=0` is "defined" and therefore on for `#ifdef`. - A typo in `#if` is silent without `-Wundef`. - `if constexpr` replaces `#if` only when every branch is valid code in every build.
- Why does #define LOGX_TRACE with no value break #if LOGX_TRACE but not #ifdef LOGX_TRACE?#ifdef only checks that the name is a macro, which it is. #if replaces the macro with its replacement list, which is empty, so the directive has no expression left to evaluate; clang reports expected value in expression. Defining configuration macros to an explicit 0 or 1 avoids the problem for #if users.
- When is if constexpr a good replacement for #if?When every branch is valid C++ in every build and the condition is a constant expression, such as a constexpr flag or a type trait. The untaken branch is discarded and, inside a template, not instantiated. It is not a replacement when a branch names functions, types or headers that only exist on another platform, because non-dependent names in the discarded branch must still be declared.
- -DLOGX_TRACE=0 makes #ifdef LOGX_TRACE false
- A misspelled macro name in #if is a compile error
- #if and #ifdef are interchangeable for configuration macros
- -Wall catches undefined identifiers in #if
- if constexpr can hide calls to functions that do not exist on this platform