Table of Contents
Previous Section Next Section

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

The #if, #ifdef, #ifndef, #else, #elif, and #endif preprocessor directives selectively compile various portions of a program. The general idea is that if the expression after an #if, #ifdef, or #ifndef is true, the code that is between one of the preceding and an #endif will be compiled; otherwise, it will be skipped over. The #endif is used to mark the end of an #if block. The #else can be used with any of the above to provide an alternative.

The general form of #if is

#if constant-expression

If the constant expression is true, the code sequence that immediately follows will be compiled.

The general form of #ifdef is

#ifdef macro-name

If the macro-name has been defined in a #define statement, the following code sequence will be compiled.

The general form of #ifndef is

#ifndef macro-name

If macro-name is currently undefined by a #define statement, the code sequence is compiled.

For example, here is the way some of these preprocessor directives work together. The code

#define ted 10

// ...

#ifdef ted
  cout << "Hi Ted\n";
#endif
  cout << "Hi Jon\n";
#if 10<9
  cout << "Hi George\n";
#endif

will print “Hi Ted” and “Hi Jon” on the screen, but not “Hi George”.

The #elif directive is used to create an if-else-if statement. Its general form is

#elif constant-expression

You can string together a series of #elifs to handle several alternatives.

You can also use #if or #elif to determine whether a macro name is defined using the defined preprocessing operator. It takes this general form:

#if defined macro-name
statement sequence
#endif

If the macro-name is defined, the statement sequence will be compiled. Otherwise, it will be skipped. For example, the following fragment compiles the conditional code because DEBUG is defined by the program:

#define DEBUG
// ...
int i=100;
// ... 
#if defined DEBUG
cout << "value of i is: " << i << endl;
#endif

You can also precede defined with the ! operator to cause conditional compilation when the macro is not defined.


Table of Contents
Previous Section Next Section