“#ifdef” inside a macro [duplicate]

2019-03-10 16:33发布

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              \

5条回答
一纸荒年 Trace。
2楼-- · 2019-03-10 16:45

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.

查看更多
Lonely孤独者°
3楼-- · 2019-03-10 16:48

How about:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif
查看更多
等我变得足够好
4楼-- · 2019-03-10 17:02

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
查看更多
可以哭但决不认输i
5楼-- · 2019-03-10 17:04

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
查看更多
劫难
6楼-- · 2019-03-10 17:07

You can do the same thing like this:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif
查看更多
登录 后发表回答