Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 5: File I/O & Advanced Projects
C ⏱ 10 min read

Preprocessor Directives and Macros

The C preprocessor runs before the compiler, transforming source code through header inclusions, macros, and conditional compilation.

What is it?

Lines beginning with `#` are preprocessor directives, such as `#include`, `#define`, `#ifdef`, `#ifndef`, and `#endif`.

Why is it used?

Header guard protection against duplicate inclusions, platform-specific compilation (Windows vs Linux), and fast inline code generation.

Detailed Explanation

Directives: • Header Guards: Prevent duplicate declaration errors when headers are included multiple times: ```c #ifndef COURSE_H #define COURSE_H // Declarations #endif ``` • Parameterized Macros: Function-like macros evaluated via text replacement before compilation: `#define SQUARE(x) ((x) * (x))`. • Always wrap macro parameters in parentheses to prevent operator precedence bugs!

Syntax Structure

Syntax Blueprint
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#ifdef _WIN32
    // Windows-specific code
#endif

Code Example

C Code
#include <stdio.h>

// Parameterized Macro with safe parentheses
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main() {
    int a = 5, b = 9;
    
    printf("Square of %d:         %d\n", a, SQUARE(a));
    printf("Square of (a + 1):    %d (Safe evaluation!)\n", SQUARE(a + 1));
    printf("Max of %d and %d:      %d\n", a, b, MAX(a, b));
    
    // Conditional Compilation check for OS
    #ifdef _WIN32
        printf("Platform Target:     Windows OS\n");
    #else
        printf("Platform Target:     POSIX / Linux OS\n");
    #endif
    
    return 0;
}

Explanation of the Code

• `((x) * (x))` guarantees `SQUARE(5 + 1)` expands to `((5 + 1) * (5 + 1)) = 36`, avoiding the infamous `5 + 1 * 5 + 1 = 11` bug. • `#ifdef _WIN32` compiles platform-specific logic dynamically.

Expected Output

Square of 5: 25 Square of (a + 1): 36 (Safe evaluation!) Max of 5 and 9: 9 Platform Target: Windows OS

Real-World Application

Cross-platform libraries like SDL, OpenGL, and SQLite use preprocessor directives to support Windows, Linux, and Android in one codebase.

Common Mistakes to Avoid

• Not putting parentheses around macro parameters (e.g. `#define SQUARE(x) x * x` causes massive arithmetic calculation bugs). • Putting semicolons at the end of `#define` statements.

Quick Practice Challenge

Write a safe macro `MIN(a, b)` that returns the smaller of two numbers.

Key Takeaways

• Preprocessor directives execute before compilation. • Always wrap macro parameters in parentheses `((x) * (x))`. • Use `#ifndef` / `#define` / `#endif` header guards in `.h` files.