Monday, 22 December 2025

Preprocessors in C++

Preprocessors in C++
The C++ preprocessor is a program that processes the source code before compilation. It handles macro substitution, file inclusion, and conditional compilation. Preprocessor commands are called directives and always begin with #.

1. #include
Used to include header files.

Types:
  • System header files
            #include <iostream>
  • User-defined header files
            #include "myfile.h"

2. #define
Used to define macros (constants or functions).

(a) Object-like macro
#define PI 3.14

(b) Function-like macro
#define SQUARE(x) ((x)*(x))

3. #undef
Used to undefine a macro.
#define MAX 100
#undef MAX

4. Conditional Compilation Directives
Used to compile code only if certain conditions are met.

#if, #elif, #else, #endif
  • #define A 10
#if A > 5
    cout << "A is greater than 5";
#else
    cout << "A is small";
#endif
  • #ifdef
#ifdef DEBUG
    cout << "Debug mode";
#endif
  • #ifndef
#ifndef PI
    #define PI 3.14
#endif

Example Program Using Preprocessor
#include <iostream>
#define MAX 50
using namespace std;
int main()
{
    #if MAX > 40
        cout << "MAX is greater than 40";
    #else
        cout << "MAX is small";
    #endif
    return 0;
}

Example Program Using Header Files
#include <iostream>
#include <cmath>
using namespace std;
int main() 
{
    cout << sqrt(16);
    return 0;
}

Creating a User-Defined Header File
Step 1: Create myheader.h

int add(int a, int b);

Step 2: Include in main program
#include <iostream>
#include "myheader.h"
using namespace std;
int main() 
{
    cout << add(5, 3);
    return 0;
}

Include Guards
Prevent multiple inclusion of the same header file.

#ifndef MYHEADER_H
#define MYHEADER_H

int add(int a, int b);

#endif

0 comments

Post a Comment