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
- Preprocessor directives are commands to the compiler executed before actual compilation.
- They are used to include files, define constants, conditionally compile code, and more.
- All directives start with
#.
2. Common Preprocessor Directives
| DirectiveDescription | |
#include | Includes a header file |
#define | Defines a macro or constant |
#undef | Undefines a macro |
#ifdef | Compiles code if a macro is defined |
#ifndef | Compiles code if a macro is not defined |
#if / #elif | Conditional compilation |
#else / #endif | Used with #if or #ifdef |
3. Example: Using #include and #define
Output:
Explanation:
#include <stdio.h>includes standard I/O functions#define PI 3.14159defines a constant macro
4. Example: Conditional Compilation
Output:
Explanation:
#ifdef DEBUGchecks ifDEBUGis defined- Conditional compilation is useful for debugging and platform-specific code
5. Key Points to Remember
- Preprocessor directives are executed before compilation
- They are not statements; no semicolon is required
- Useful for including files, defining constants, and conditional compilation
- Commonly used for code modularity and portability