bers
bers

Reputation: 5773

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

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?

Upvotes: 1

Views: 142

Answers (2)

mcendu
mcendu

Reputation: 440

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)

Upvotes: 1

HolyBlackCat
HolyBlackCat

Reputation: 96176

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

Upvotes: 5

Related Questions