"#ifdef" inside a macro

C++C Preprocessor

C++ Problem Overview


> 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	         	\

						

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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 - C++

You can do the same thing like this:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif

Solution 5 - C++

How about:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonGenXView Question on Stackoverflow
Solution 1 - C++Roger LipscombeView Answer on Stackoverflow
Solution 2 - C++Oliver CharlesworthView Answer on Stackoverflow
Solution 3 - C++Paul MantaView Answer on Stackoverflow
Solution 4 - C++antlersoftView Answer on Stackoverflow
Solution 5 - C++Miguel GrinbergView Answer on Stackoverflow