C++ Preprocessor Directive


What are Preprocessor Directives?

  • The preprocessor directives are the lines that are included in a program which begins with the # and it is different from the typical source code.
  • They are invoked by the compiler to process the programs before compilation. The preprocessor directive is placed at the top of the source code in a separate line beginning with the character # and followed by a directive name.
  • The preprocessor directive statement cannot be with semi colon. Some of the examples of preprocessor directives are #define, #include, #indef, etc.

Types of Preprocessor Directives

Let us discuss preprocessor directives types:


The macros are the piece of code in a program which is given some name and whenever this name occurs then the compiler replaces the name with the  actual code. The #define directive is used to define a macro.

Let us have a look at the example to understand this:

We can also pass the arguments to macros. Macros defined with arguments work similarly as functions.

Let us have a look at the example:

File Inclusion

In this preprocessor directive it tells the compiler to include a file in the source code.

There are two types of files which can be included by the user in a program:

1. Header File

The header files contains the definition of predefined functions like cin, cout, etc. These files must be included for working with these functions; different functions are declared in different header files. For example functions which perform string operations are in ‘string’ file.



In this syntax the filename is the name of the file that to be included. The ‘<’ and ‘>’ brackets tells the compiler to check for the file in the standard directory.

2. User defined Files

When the program is very large so it is good to divide it into smaller files and include whenever needed. These types of files are user defined files.


#include “filename”

  • Conditional Compilation: The conditional compilation directives are type of directives which helps to compile a specific code of the program or to skip compilation of some specific part of the program based on some conditions. We can perform this with the help of two preprocessing commands ifdef and endif.


  • Other Directives: There are some other directives apart from the directives discussed above. There are two directives which are not used:
  1. #undef Directive:  It is used to undefine an existing macro.


#undef LIMIT

By using this statement it will undefine the existing macro LIMIT. After this statement every “ifdef LIMIT” statement will evaluate to false.

  1. #pragma Directive: This directive is a special directive as it is used to turn on or off some of the features and it is a compiler specific which means it vary from compiler to compiler.


Share this website !!!
Facebook Twitter Linkedin