C++ 布尔运算符可以与预处理器一起使用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3390603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can boolean operators be used with the preprocessor?
提问by Wesley
I wondering if it possible to have a preprocessor OR or AND statement? I have this code where I want to run under _DEBUG
or _UNIT_TEST
tags(?).
我想知道是否有可能有一个预处理器 OR 或 AND 语句?我有这个代码,我想在_DEBUG
或_UNIT_TEST
标签下运行(?)。
What I want is something like the following:
我想要的是以下内容:
#if _DEBUG || _UNIT_TEST
//Code here
#endif
If this is not possible, is there a workaround to achieve the same thing without having to duplicate the code using a #elseif
?
如果这是不可能的,是否有一种解决方法可以实现相同的目的而不必使用#elseif
?
回答by Kirill V. Lyadvinsky
#if defined _DEBUG || defined _UNIT_TEST
//Code here
#endif
You could use AND and NOT operators as well. For instance:
您也可以使用 AND 和 NOT 运算符。例如:
#if !defined _DEBUG && defined _UNIT_TEST
//Code here
#endif
回答by Roman Starkov
#if
takes anyC++ expression of integral type(1) that the compiler manages to evaluate at compile time. So yes, you can use ||
and &&
, as long as you use defined(SOMETHING)
to test for definedness.
#if
接受编译器在编译时设法计算的任何整数类型 (1) 的 C++ 表达式。所以是的,你可以使用||
and &&
,只要你defined(SOMETHING)
用来测试定义性。
(1): well, it's a bit more restricted than that; for the nitty-gritty see the restrictions here(at "with these additional restrictions").
(1):嗯,它比那更受限制;有关细节,请参阅此处的限制(在“带有这些附加限制”)。
回答by AshleysBrain
#if defined(_DEBUG) || defined(_UNIT_TEST)
//Code here
#endif
Also for the record, it's #elif
, not #elseif
.
另外为了记录,它是#elif
,不是#elseif
。