How to expand a Boolean expression in the C++ preprocessor?

113 Views Asked by At

The following code does not expand the Boolean expression, see also https://godbolt.org/z/YqbazT3eo:

#define EXPAND(x) x

#define SWITCH false
EXPAND(SWITCH || defined(_DEBUG))

How do I do it correctly so that I can do

#define FLAG EXPAND(SWITCH || defined(_DEBUG))

(or similar) and FLAG will not depend on later changes to SWITCH?

2

There are 2 best solutions below

6
HolyBlackCat On BEST ANSWER

FLAG will not depend on later changes to SWITCH?

The only way is this:

#if SWITCH || defined(_DEBUG)
#define FLAG 1
#else
#define FLAG 0
#endif
0
mcendu On

The C/C++ preprocessor is dumb when not handling conditionals; it only expands whatever is #defined, and don't care about the rest – meaning it has no ability to deduce that something is a constant expression and evaluate it. Also defined() only hold special meaning in #if directives and friends.

Redefinitions later in a file would emit a warning in modern compilers, but before the redefinition the macro still expands to the old value. Thus

#define EXPAND(x) x

#define SWITCH false
EXPAND(SWITCH || defined(_DEBUG))

#define SWITCH true

expands to the following (GCC 13.2):

false || defined(_DEBUG)