“#ifdef” inside a macro [duplicate]

烂漫一生 提交于 2019-12-03 05:28:26

问题


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              \

回答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.




回答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



回答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



回答4:


You can do the same thing like this:

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



回答5:


How about:

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


来源:https://stackoverflow.com/questions/7246512/ifdef-inside-a-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!