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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:44:56  来源:igfitidea点击:

Can boolean operators be used with the preprocessor?

c++c-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 _DEBUGor _UNIT_TESTtags(?).

我想知道是否有可能有一个预处理器 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

#iftakes 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