Preprocessor Directives in C

Preprocessor Directives in C


Introduction

Preprocessor directives are special instructions in C that are processed before compilation.

👉 They start with # and are used to control the compilation process.


What are Preprocessor Directives?

Preprocessor directives are:
👉 Commands given to the compiler before actual compilation starts


Why Use Preprocessor Directives?

  • ✔ Include files
  • ✔ Define constants
  • ✔ Control compilation
  • ✔ Improve code readability

Types of Preprocessor Directives

  • #include
  • #define
  • #undef
  • Conditional directives (#if, #else, etc.)

1. #include Directive

👉 Used to include header files

#include <stdio.h>

2. #define Directive

👉 Used to define constants

#define PI 3.14

Example

#include <stdio.h>

#define PI 3.14

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

printf("Area = %.2f", area);

return 0;
}

Output

Area = 12.56

3. #undef Directive

👉 Used to remove a defined macro

#undef PI

4. Conditional Compilation

👉 Used to compile code based on condition

#include <stdio.h>

#define VALUE 10

int main() {
#if VALUE > 5
printf("Value is greater than 5");
#else
printf("Value is small");
#endif

return 0;
}

Output

Value is greater than 5

Preprocessor Directives Table

Directive Purpose
#include Include header files
#define Define constants
#undef Remove macro
#if Conditional compilation

Important Notes

  • No semicolon needed
  • Processed before compilation
  • Case-sensitive
  • Used globally

Common Mistakes

  • ❌ Using semicolon after #define
  • ❌ Wrong macro usage
  • ❌ Forgetting header files
  • ❌ Misusing conditions

Pro Tips

  • ✔ Use meaningful macros
  • ✔ Avoid overuse of macros
  • ✔ Use conditional compilation wisely
  • ✔ Keep code clean

Conclusion

Preprocessor directives are powerful tools in C that help control compilation and improve code efficiency.

Master them for better programming practices.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C