Can boolean operators be used with the preprocessor?

C++C Preprocessor

C++ Problem Overview


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(?).

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?

C++ Solutions


Solution 1 - C++

#if defined _DEBUG || defined _UNIT_TEST 
  //Code here 
#endif 

You could use AND and NOT operators as well. For instance:

#if !defined _DEBUG && defined _UNIT_TEST 
  //Code here 
#endif 

Solution 2 - C++

#if takes any C++ 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.

(1): well, it's a bit more restricted than that; for the nitty-gritty see the restrictions here (at "with these additional restrictions").

Solution 3 - C++

#if defined(_DEBUG) || defined(_UNIT_TEST)
  //Code here
#endif

Also for the record, it's #elif, not #elseif.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWesleyView Question on Stackoverflow
Solution 1 - C++Kirill V. LyadvinskyView Answer on Stackoverflow
Solution 2 - C++Roman StarkovView Answer on Stackoverflow
Solution 3 - C++AshleysBrainView Answer on Stackoverflow