Preprocessor Conditionals [C++ Reference]
Keywords: preprocessor,preprocessor_if
Date: 2008-10-14T15:42:05-0700

[[Preprocessor Conditionals]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

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

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •