Silicomancer Silicomancer - 1 year ago 131
C Question

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:


I am using it in my code like this:

#define LOG(foo) { log(foo); }
#define LOG(foo)

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

When changing the macro argument to:


everything works.

I understand that
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?

a3f a3f
Answer Source
#define hehe true
#if hehe
#error hehe
#error haha

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download