Preprocessor Conditionals

#if, #ifdef, #ifndef, #else, #elif, #endif

These six preprocessor commands give simple logic control to the compiler. As a file is being compiled, you can use these commands to cause certain lines of code to be included or not included.

     #if expression

If the value of expression is true, then the code that immediately follows the command will be compiled.

     #ifdef macro

If the macro has been defined by a #define statement, then the code immediately following the command will be compiled.

     #ifndef macro

If the macro has not been defined by a #define statement, then the code immediately following the command will be compiled.

A few side notes: The command #elif is simply a horribly truncated way to say “elseif” and works like you think it would. You can also throw in a “defined” or ”!defined” after an #if to get added functionality.

Here's an example of all these:

     #ifdef DEBUG
       cout << "This is the test version, i=" << i << endl;
     #else
       cout << "This is the production version!" << endl;
     #endif

You might notice how that second example could make debugging a lot easier than inserting and removing a million “cout”s in your code.

Related topics: #define