Preprocessor in C
Before a C program is compiled, it goes through a special step called preprocessing.
The preprocessor prepares your code for compilation by handling directives such as macros, file inclusion and conditional compilation.
Why Preprocessor Exists
The preprocessor helps programmers:
- Reuse code efficiently
- Improve readability
- Control compilation behavior
- Avoid repeated values and magic numbers
Common Preprocessor Directives
#include– includes header files#define– defines constants or macros#undef– removes a macro#ifdef,#ifndef– conditional compilation#if,#else,#endif
#include Directive
Used to include header files.
#include <stdio.h>
#include "myfile.h"
Angle brackets are used for system headers, while quotes are used for user-defined files.
#define Directive (Macros)
Macros replace values before compilation.
#define PI 3.14
#define MAX 100
Whenever PI appears in the code, it is replaced with 3.14.
Macro with Expression
#define SQUARE(x) (x * x)
int result = SQUARE(5);
Macros do not perform type checking, so parentheses are important.
Conditional Compilation
Conditional compilation allows parts of code to compile only if a condition is met.
#define DEBUG
#ifdef DEBUG
printf("Debug mode enabled");
#endif
This is commonly used in large projects for debugging.
Real-World Example
In real applications, preprocessor directives are used to:
- Enable or disable logging
- Support different operating systems
- Define application-wide constants
Quiz
Q1: When does the preprocessor run?
Before compilation starts.
Q2: Which directive is used to define constants?
#define
Q3: Are macros type-safe?
No, macros do not perform type checking.
Q4: Which directive removes a macro?
#undef
Q5: Is #include executed at runtime?
No, it is processed before compilation.
Mini Practice
- Create a macro for calculating area of a circle
- Use conditional compilation for debug messages
- Try removing a macro using
#undef