Pre-Processor Directives in C
Introduction
Pre-processor directives in C are special instructions given to the compiler before actual
compilation begins. These directives allow inclusion of header files, definition of macros,
and conditional compilation. They start with '#' and do not require a semicolon.
Commonly Used Pre-Processor Directives
1. #include
Used to include external files, typically header files.
There are two types:
1. Standard header files: Enclosed in < > (angle brackets), searched in system directories.
#include <stdio.h> // Includes standard input-output functions
2. User-defined header files: Enclosed in "", searched in the current directory.
#include "myheader.h" // Includes a user-defined header file
2. #define
Used to define constants or macros.
#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))
3. #undef
Used to undefine a previously defined macro.
#define TEMP 100
#undef TEMP
4. Conditional Compilation Directives
a) #if, #else, #elif, #endif
Used to conditionally include or exclude parts of the code during compilation.
#define DEBUG 1
#if DEBUG
printf("Debug mode is ON\n");
#else
printf("Debug mode is OFF\n");
#endif
b) #ifdef (If Defined)
Checks if a macro is defined.
#define PI 3.14159
#ifdef PI
printf("PI is defined\n");
#endif
c) #ifndef (If Not Defined)
Checks if a macro is not defined.
#ifndef MAX
#define MAX 100
#endif
5. #pragma
Provides special instructions to the compiler.
#pragma once // Ensures the file is included only once
Advantages of Pre-Processor Directives
1. Improves Code Readability – By using macros and header files.
2. Reduces Code Duplication – By defining macros and constants.
3. Enhances Portability – By conditionally compiling platform-specific code.
4. Speeds Up Compilation – By handling reusable code effectively.