Defference Between #if #else #endif and Regular, if, otherwise

As the title says, I was interested to know what the differences are between using

#if
   DoWork();
#else
   DoAnotherWork();
#endif

and

if (debug)
   DoWork();
else
   DoAnotherWork();
+5
source share
3 answers
if (debug)
    DoWork();
else
    DoAnotherWork();

The above code will be compiled and the condition will be checked at runtime.

#if
    DoWork();
#else
    DoAnotherWork();
#endif

These instructions will be checked at compile time.

So, if the #if condition is true, DoWork (); DoAnotherWork () will be compiled otherwise; will be compiled. Where, as in the previous example, all code including the if statement will be compiled.

Read it in the Preprocessor Directives

Preprocessor directives

+11
source

First, the Preprocessor Directive and the second Logical instruction .

+9

The first version uses preprocessor directives. These are instructions for the compiler itself only to compile certain statements. As a result, the executable will contain only compiled instructions. Therefore, the condition should be something that can be evaluated at compile time.

The second version is evaluated at runtime. The compiler will compile all instructions, as well as logic to evaluate the state if. All statements will be included in the resulting executable. And which statement is actually executed will be determined when your code runs.

+6
source

All Articles