Preprocessor Directives in C Programming (Complete Guide with Examples)


This tutorial explains preprocessor directives in C, which are instructions executed before compilation. It covers common directives like #include, #define, #ifdef, and practical examples to improve code modularity, readability, and maintainability.

1. What are Preprocessor Directives

  1. Preprocessor directives are commands to the compiler executed before actual compilation.
  2. They are used to include files, define constants, conditionally compile code, and more.
  3. All directives start with #.

2. Common Preprocessor Directives

DirectiveDescription
#includeIncludes a header file
#defineDefines a macro or constant
#undefUndefines a macro
#ifdefCompiles code if a macro is defined
#ifndefCompiles code if a macro is not defined
#if / #elifConditional compilation
#else / #endifUsed with #if or #ifdef

3. Example: Using #include and #define


#include <stdio.h>
#define PI 3.14159

int main() {
float r = 5.0;
float area = PI * r * r;

printf("Area of circle: %.2f\n", area);
return 0;
}

Output:


Area of circle: 78.54

Explanation:

  1. #include <stdio.h> includes standard I/O functions
  2. #define PI 3.14159 defines a constant macro

4. Example: Conditional Compilation


#include <stdio.h>
#define DEBUG

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

printf("Program running\n");
return 0;
}

Output:


Debugging mode ON
Program running

Explanation:

  1. #ifdef DEBUG checks if DEBUG is defined
  2. Conditional compilation is useful for debugging and platform-specific code

5. Key Points to Remember

  1. Preprocessor directives are executed before compilation
  2. They are not statements; no semicolon is required
  3. Useful for including files, defining constants, and conditional compilation
  4. Commonly used for code modularity and portability