"#ifdef" inside a macro [duplicate]
Possible Duplicate:
#ifdef inside #define
How do I use the character "#" successfully inside a Macro? It screams when I do something like that:
#define DO(WHAT) \
#ifdef DEBUG \
MyObj->WHAT() \
#endif \
Solution 1:
You can't do that. You have to do something like this:
#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT) do { } while(0)
#endif
The do { } while(0)
avoids empty statements. See this question, for example.
Solution 2:
It screams because you can't do that.
I suggest the following as an alternative:
#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif
Solution 3:
It seems that what you want to do can be achieved like this, without running into any problems:
#ifdef DEBUG
# define DO(WHAT) MyObj->WHAT()
#else
# define DO(WHAT) while(false)
#endif
Btw, better use the NDEBUG
macro, unless you have a more specific reason not to. NDEBUG
is more widely used as a macro that means no-debugging. For example the standard assert
macro can be disabled by defining NDEBUG
. Your code would become:
#ifndef NDEBUG
# define DO(WHAT) MyObj->WHAT()
#else
# define DO(WHAT) while(false)
#endif
Solution 4:
You can do the same thing like this:
#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif