#if is a preprocessor directive that works as a pre-compilation if statement. Its purpose is to facilitate portability.

#if is followed by some condition, and if the preprocessor does not determine the condition to be something it's programmed to consider "true" under the current conditions, it simply fails to include in the final compiled program everything between the #if and the corresponding #endif later in the code. There are also #elif ("else if") and #else directives.

Example: lame_insult.cpp

#include <iostream.h>

void main () {
     cout << "You are using a macintosh, you dirty tree-hugging hippie.";
     cout << "You are using windows, you whore.";
     cout << "What the hell is wrong with you?";
The above will compile a simple program that contains only one of the three statements in the program, depending on whether they're compiling for macintosh, windows or something else. This kind of thing is how you write cross-platform code that uses the same C files-- abstract all your OS-interfacing code into functions in specific header files, write seperate versions of each header file for each OS, then use #if statements to decide at compile time which header to #include.

See also #ifdef

ariels says re #if: Note a difference: TARGET_OS_MAC must only be defined, but TARGET_OS_WINDOWS must be defined and != 0.

Log in or register to write something here or to contact authors.