#if 0作为定义 [英] #if 0 as a define
问题描述
我需要一种方法来定义FLAGS_IF
宏(或等效宏),以使
FLAGS_IF(expression)
<block_of_code>
FLAGS_ENDIF
在调试中进行编译时(例如使用特定的编译器开关)会编译为
if (MyFunction(expression))
{
<block_of_code>
}
而在发布时不会产生任何指令,就像这样
#if 0
<block_of_code>
#endif
由于对 C /C ++预处理器一无所知,我想不出任何幼稚的方式(因为#define FLAGS_IF(x) #if 0
甚至没有编译),您能帮上忙吗?>
我需要一个解决方案:
- 如果
<block_of_code>
内部存在*/
,不会弄乱
- 即使在任何深度的内联函数中,也可以确保在释放中生成0条指令(我想这不包括
if (false){<block_of_code>}
吧?) - 是否符合标准
以下应做您想做的事情:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x))) {
# define FLAGS_ENDIF }
#else
# define FLAGS_IF(x) if(0) {
# define FLAGS_ENDIF }
#endif
if(0)应该不变成任何指令,或者至少在大多数编译器中都这样.
编辑:Hasturkun指出您确实不需要FLAGS_ENDIF,因此可以这样编写代码:
FLAGS_IF(expression) {
<block_of_code>
}
具有以下宏:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x)))
#else
# define FLAGS_IF(x) if(0)
#endif
I need a way to define a FLAGS_IF
macro (or equivalent) such that
FLAGS_IF(expression)
<block_of_code>
FLAGS_ENDIF
when compiling in debug (e.g. with a specific compiler switch) compiles to
if (MyFunction(expression))
{
<block_of_code>
}
whereas in release does not result in any instruction, just as it was like this
#if 0
<block_of_code>
#endif
In my ignorance on the matter of C/C++ preprocessors I can't think of any naive way (since #define FLAGS_IF(x) #if 0
does not even compile) of doing this, can you help?
I need a solution that:
- Does not get messed up if
*/
is present inside<block_of_code>
- Is sure to generate 0 instructions in release even inside inline functions at any depth (I guess this excludes
if (false){<block_of_code>}
right?) - Is standard compliant if possible
The following should do what you want:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x))) {
# define FLAGS_ENDIF }
#else
# define FLAGS_IF(x) if(0) {
# define FLAGS_ENDIF }
#endif
The if(0) should turn into no instructions, or at least it does so on most compilers.
Edit: Hasturkun commented that you don't really need the FLAGS_ENDIF, so you would instead write your code like this:
FLAGS_IF(expression) {
<block_of_code>
}
with the follow macros:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x)))
#else
# define FLAGS_IF(x) if(0)
#endif
这篇关于#if 0作为定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!