C++ Getting started with C++ Preprocessor


Example

The preprocessor is an important part of the compiler.

It edits the source code, cutting some bits out, changing others, and adding other things.

In source files, we can include preprocessor directives. These directives tells the preprocessor to perform specific actions. A directive starts with a # on a new line. Example:

#define ZERO 0

The first preprocessor directive you will meet is probably the

#include <something>

directive. What it does is takes all of something and inserts it in your file where the directive was. The hello world program starts with the line

#include <iostream>

This line adds the functions and objects that let you use the standard input and output.

The C language, which also uses the preprocessor, does not have as many header files as the C++ language, but in C++ you can use all the C header files.


The next important directive is probably the

#define something something_else

directive. This tells the preprocessor that as it goes along the file, it should replace every occurrence of something with something_else. It can also make things similar to functions, but that probably counts as advanced C++.

The something_else is not needed, but if you define something as nothing, then outside preprocessor directives, all occurrences of something will vanish.

This actually is useful, because of the #if,#else and #ifdef directives. The format for these would be the following:

#if something==true
//code
#else
//more code
#endif

#ifdef thing_that_you_want_to_know_if_is_defined
//code
#endif

These directives insert the code that is in the true bit, and deletes the false bits. this can be used to have bits of code that are only included on certain operating systems, without having to rewrite the whole code.