C++: Preprocessor Directives

Preprocessor Directives

In this video, we give some examples of C++ preprocessor directives and explain their usage. Preprocessor directives begin with the # character, which is sometimes called a pound, sharp, or number symbol. Before C++ code is compiled, it runs through a preprocessor that prepares the code for compilation. Here we give an example of a simple program with a #define directive.

#define TEN 10

int main()
{
    int iTenSquared = TEN*TEN;
    return 0;
}

If we preprocess the program above, we get:




int main()
{
    int iTenSquared = 10*10;
    return 0;
}

Notice that the #define directive is removed and TEN has been replace by 10 inside the main function. Once this preprocessing is done, the preprocessed code gets compiled.

We can use the #define directive to create more complex substitution macros. These macros look and act somewhat like functions. Here, we show a program with a simple macro that gives the minimum of two values.

#define MIN(a,b) (a<b?a:b)

int main()
{
    double dMin = MIN(4,2);
    return 0;
}

If we preprocess this code, we get:




int main()
{
    double dMin = (4<2?4:2);
    return 0;
}

Notice that the values 4 and 2 have been substituted into the macro in place of a and b, respectively. The parentheses act like an argument list for macros, where the "arguments" are pasted into the corresponding place in the macros definition.

The #include directive has been used extensively in previous programs. This directive just pastes the code of the included file in place of the #include directive. An included file may have other files included in it via the #include directive. Those files may include other files and so on. So, a single include directive may add a substantial amount of code.

Preprocessor directives may also be use to create conditional compilation. Just like a standard if statement, the preprocessor #if directive can have optional else and elseif branches. The elseif is given by the #elif directive and the else is simply #else. Below, we have an example of a program which uses conditional compilation.

#define BRANCH1 0
#define BRANCH2 1

int main()
{
    int iValue;
#if BRANCH1
    iValue = 0;
#elif BRANCH2
    iValue = 1;
#else
    iValue = 2;
#endif
    return 0;
}

The preprocessed version of this code looks like this:





int main()
{
    int iValue;



    iValue = 1;



    return 0;
}

Notice that the code for the #if and #else branches is not included. This means that that code is never compiled. Since the #if branch is false and the #elif branch is true, only its code is compiled.