01. #include, #define & Function-Like Macros

🟒 Difficulty: Beginner to Intermediate | Text Replacement, Macro Parenthesization & Multi-Statement Idioms

πŸ“– Definition

The #include directive instructs the preprocessor to replace the directive line with the entire raw text contents of the specified header file. The #define directive defines **macros**β€”literal text replacement rules that substitute identifier tokens across the source code before compiler lexical analysis occurs.

🎯 Why It Is Used

  • Header Inclusions: Importing standard system declarations (#include <stdio.h>) or local project header declarations (#include "my_header.h").
  • Symbolic Constants: Defining system-wide configuration values (e.g., #define MAX_BUFFER_SIZE 1024).
  • Function-Like Inline Utilities: Writing generic, type-agnostic inline macro expressions (e.g., #define MIN(a, b) (((a) < (b)) ? (a) : (b))).

βš™οΈ How It Works: #include Search Paths

  • #include <header.h> (Angle Brackets): Searches strictly in system standard library directories (e.g. /usr/include, MinGW include path).
  • #include "header.h" (Double Quotes): Searches first in the current local source file directory, falling back to system library directories if not found locally.

πŸ“ Syntax

// 1. System Header vs Local Header
#include <stdio.h>      // System include
#include "my_config.h"  // Local include

// 2. Object-Like Macro
#define MAX_CONNECTIONS 100

// 3. Function-Like Macro (ALWAYS PARENTHESIZE ARGUMENTS & OVERALL EXPRESSION!)
#define SQUARE(x) ((x) * (x))

// 4. Safe Multi-Statement Macro Wrapper Idiom
#define SAFE_LOG(msg) do { \
    printf("[LOG] %s\n", (msg)); \
} while(0)

πŸ”€ Parenthesization & Side-Effect Traps

Because macros perform raw literal text substitution, omitting parentheses around macro arguments leads to operator precedence bugs:

// BAD MACRO (No parentheses)
#define BAD_SQUARE(x) x * x
// BAD_SQUARE(2 + 3) expands to: 2 + 3 * 2 + 3 = 2 + 6 + 3 = 11 (WRONG! Expected 25)

// GOOD MACRO (Parenthesized)
#define GOOD_SQUARE(x) ((x) * (x))
// GOOD_SQUARE(2 + 3) expands to: ((2 + 3) * (2 + 3)) = 5 * 5 = 25 (CORRECT!)

🌱 Beginner Example: Symbolic Constants

#include <stdio.h>

#define PI 3.1415926535
#define BUFFER_SIZE 50

int main(void) {
    double radius = 5.0;
    double area = PI * radius * radius;

    printf("Circle Area (PI = %.5f): %.2f\n", PI, area);
    printf("Max Buffer Size: %d bytes\n", BUFFER_SIZE);
    return 0;
}

🌼 Intermediate Example: Parenthesized Function-Like Macro

#include <stdio.h>

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

int main(void) {
    int x = 15, y = 25;
    printf("Larger value between %d and %d: %d\n", x, y, MAX(x, y));
    printf("Precedence Check MAX(10+5, 2*8): %d\n", MAX(10 + 5, 2 * 8));
    return 0;
}

🌲 Advanced Example: The do { ... } while(0) Macro Wrapper Idiom

#include <stdio.h>

// do { ... } while(0) ensures macro behaves as a SINGLE atomic statement
// that seamlessly integrates with if-else blocks!
#define SWAP_INTS(a, b) do { \
    int temp = (a); \
    (a) = (b); \
    (b) = temp; \
} while(0)

int main(void) {
    int m = 100, n = 200;

    if (m < n)
        SWAP_INTS(m, n); // Works cleanly inside single-line if!
    else
        printf("No swap needed.\n");

    printf("Swapped values: m = %d, n = %d\n", m, n);
    return 0;
}

πŸ” Line-by-Line Explanation

  • #include <stdio.h>: Includes standard I/O library prototypes by replacing line with system header text.
  • #define MAX(a, b) (((a) > (b)) ? (a) : (b)): Expands inline at call site without stack frame overhead.
  • do { ... } while(0): Wraps multi-statement macros into a single statement block, preventing syntax errors when placed inside unbraced if-else structures.

πŸ’» Expected Terminal Output

Circle Area (PI = 3.14159): 78.54
Max Buffer Size: 50 bytes
Larger value between 15 and 25: 25
Precedence Check MAX(10+5, 2*8): 16
Swapped values: m = 200, n = 100

⚠️ Common Mistakes & Pitfalls

  • Side-Effect Double Evaluation: Calling MAX(x++, y) expands to (((x++) > (y)) ? (x++) : (y)), evaluating x++ TWICE and corrupting x! Use C99 inline functions for expressions with side effects.
  • Adding Trailing Semicolons to #define: Writing #define SIZE 100; causes syntax errors when expanded inside statements like int arr[SIZE]; (expands to int arr[100;];!).

πŸ“Œ Important Rules & Limitations

  • Always wrap function-like macro arguments and overall expressions in parentheses.
  • Do NOT place trailing semicolons at the end of #define macro declarations.
  • Use do { ... } while(0) for multi-statement macros.

🌐 Multilingual Explanation: English

The preprocessor performs text replacement before compilation. Use parentheses around function-like macro arguments to prevent operator precedence bugs, and use do { ... } while(0) for multi-line macros.

🌐 Multilingual Explanation: Hindi (Roman Script)

Preprocessor compilation se pehle text substitution karta hai. Function-like macros mein arguments ko hamesha parenthesis (x) mein rakhein taaki operator precedence ki galtiyan na ho.

🌐 Multilingual Explanation: Marathi (Roman Script)

Preprocessor text replacement karto. Function-like macros sathi nehamhi arguments aani poorna expression parenthesis (x) madhye dhyave.

❓ Practice Questions

  1. What is the difference between #include <header.h> and #include "header.h"?
  2. Why does #define SQUARE(x) x * x produce an incorrect result for SQUARE(2 + 3)?
  3. Why is the do { ... } while(0) wrapper used for multi-statement macros?

πŸš€ Practical Coding Challenge

Write a C program named safe_min_max.c that defines a macro CLAMP(val, min_val, max_val) that restricts val between min_val and max_val using ternary operators with full parenthesization.

🧭 Navigation & Breadcrumbs

← Module 17 Guide | Next: 02. Conditional Compilation →