Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can boolean operators be used with the preprocessor?

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?

like image 859
Wesley Avatar asked Aug 02 '10 18:08

Wesley


People also ask

Which operator is used for preprocessing in C?

In C preprocessor, a character sequence enclosed by quotes is considered a token and its content is not analyzed. This means that macro names within quotes are not expanded. If you need an actual argument (the exact sequence of characters within quotes) as a result of preprocessing, use the # operator in macro body.

Which is not preprocessor operator?

Ans: #elseif is not any preprocessor directive, but #elif is.

Which operator is known as preprocessor directive?

All Preprocessor directives begin with the # (hash) symbol. C++ compilers use the same C preprocessor. The preprocessor is a part of the compiler which performs preliminary operations (conditionally compiling code, including files etc...) to your code before the compiler sees it.


2 Answers

#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  
like image 139
Kirill V. Lyadvinsky Avatar answered Sep 21 '22 06:09

Kirill V. Lyadvinsky


#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").

like image 40
Roman Starkov Avatar answered Sep 22 '22 06:09

Roman Starkov