C++ Preprocessor

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us have a look at preprocessors, types and sample program for better understanding the concepts.

Introduction of Preprocessor

Preprocessors are the directives which tell the compiler to preprocess the source code before compilation begins. All of these preprocessor directives begin with a ‘#’ (hash) symbol and it is placed at the beginning of a statement in a C/C++ program. 

Some examples: #include#define#ifndef etc.

Types of Preprocessor

The different types of preprocessor directives are:

  • Macros
  • File Inclusion
  • Conditional Compilation

Macros

Macros are a part of code in a program which is given some name. Whenever this name is found by the compiler, it replaces the name with the actual piece of code. The #define directive is used to define a macro.

Program for macros

#include <iostream>   
// macro definition 
#define LIMIT 5 
int main() 
{ 
    for (int i = 0; i < LIMIT; i++) { 
        std::cout << i << "\n"; 
    } 
    return 0; 
}

Output

0
1
2
3
4

File Inclusion

This type of preprocessor directive tells the compiler to include a file in the source code program.

It is of two types:

Header File or Standard files

The header files include the definition of pre-defined functions like cin, cout, etc. These files must be included for working with desired functions. 

Syntax

#include< file_name >

user-defined files

When a program becomes very comprehensive, it is a good method to divide it into smaller files and include whenever required. These types of files are called user-defined files.

Syntax

#include"filename"

Conditional Compilation

Conditional Compilation directives are a kind of directives that helps to compile a specific part of the program based on some conditions. This can be done with the help of two preprocessing commands such as ‘ifdef‘ and ‘endif

Syntax

#ifdef macro_name
    statement1;
    statement2;
    statement3;
    .
    .
    .
    statementN;
#endif

Leave a Comment

Your email address will not be published. Required fields are marked *