Loading...

Preprocessors in C

The C Preprocessor (CPP) is a tool that processes the source code before compilation. It handles directives that begin with #.

Types of Preprocessor Directives

1. Macro Definition (#define)

Used to define constants or macros.

#define PI 3.14
#define SQUARE(x) (x * x)

printf("Value of PI: %f", PI);
printf("Square of 5: %d", SQUARE(5));

2. File Inclusion (#include)

Includes header files in the program.

  • #include <stdio.h> (Standard library file)
  • #include "myfile.h" (User-defined file)
#include <stdio.h>
#include "myheader.h"

3. Conditional Compilation (#ifdef, #ifndef, #endif)

Used to compile specific parts of code based on conditions.

#define DEBUG

#ifdef DEBUG
    printf("Debugging mode ON\n");
#endif

4. Undefining a Macro (#undef)

Used to remove a macro definition.

#define VALUE 100
#undef VALUE

5. Other Preprocessor Directives

  • #pragma: Provides compiler-specific instructions.
  • #error: Generates an error message during compilation.

Example Program

#include <stdio.h>
#define PI 3.1415
#define AREA(r) (PI * r * r)

int main() {
    int radius = 5;
    printf("Area of Circle: %f\n", AREA(radius));
    return 0;
}

The C preprocessor helps in code modularity and efficiency by allowing macros, conditional compilation, and file inclusion.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!