Silicomancer
Silicomancer

Reputation: 9196

Using true and false in macros in C99

I am writing some code using a customized gcc compiler that supports a subset of C99. Using compiler options I defined a macro like this:

ENABLE_LOGGING=true

I am using it in my code like this:

#if ENABLE_LOGGING
#define LOG(foo) { log(foo); }
#else
#define LOG(foo)
#endif

It just turned out that this doesn't work reliably. Sometimes the LOG containing code is used, sometimes the emtpy LOG is used (same project, same compiler setting).

When changing the macro argument to:

ENABLE_LOGGING=1

everything works.

I understand that true could be unknown to the preprocessor. But then, why does it work most times? And why do I get no warning or error during compilation for the modules where it doesn't work?

Upvotes: 2

Views: 794

Answers (1)

a3f
a3f

Reputation: 8657

#define hehe true
#if hehe
#error hehe
#else
#error haha
#endif

will #error haha because hehe expands to true and true will be substitued by a 0 because

§6.10.1¶4 all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0

But if you happen to #include <stdbool.h> before your #if, it will #error hehe, because

§7.18 The header defines four macros. …

¶3 The remaining three macros are suitable for use in #if preprocessing directives. They are true which expands to the integer constant 1

Upvotes: 6

Related Questions