C Preprocessor and Macros

C Preprocessor and Macros
The C Preprocessor and Macros runs before the actual compilation of the program.
It processes instructions beginning with the # symbol, called preprocessor directives.
These directives help include files, define constants, create macros, and control compilation.
📌 Common Preprocessor Directives
| Directive | Purpose |
|---|---|
#include | Includes header files |
#define | Defines macros or constants |
#undef | Removes a defined macro |
#ifdef | Checks if macro is defined |
#ifndef | Checks if macro is not defined |
#if, #elif, #else, #endif | Conditional compilation |
#pragma | Compiler-specific instructions |
1️⃣ #include Directive
Used to insert the contents of another file.
2️⃣ #define (Macros and Constants)
✔ Define a constant:
✔ Define a macro function:
👀 Warning: Macro without parentheses can cause errors:
❌ Wrong:
✔ Correct:
3️⃣ #undef
Removes a defined macro.
4️⃣ Conditional Compilation
Used when compiling different environments (debug mode, Windows/Linux, etc.)
#ifdef Example:
#ifndef Example:
✔ #if / #elif / #else
5️⃣ Multi-line Macros
Use \ to continue on the next line:
6️⃣ Predefined Macros
C provides built-in macros:
| Macro | Meaning |
|---|---|
__DATE__ | Current compilation date |
__TIME__ | Current compilation time |
__FILE__ | Current filename |
__LINE__ | Line number in file |
__STDC__ | Whether compiler conforms to ANSI C |
Example:
Advantages of Macros
✔ Faster execution (no function call)
✔ Easy constant management
✔ Useful in debugging
✔ Platform-specific compilation
Disadvantages
❌ Can cause unexpected behavior
❌ Hard to debug
❌ No type checking
🧠 Summary
| Feature | Example |
|---|---|
| Constant | #define PI 3.14 |
| Macro function | #define SQUARE(x) ((x)*(x)) |
| Include file | #include <stdio.h> |
| Conditional compile | #ifdef DEBUG |
