First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Preprocessor and macros

Preprocessor directives, macros, conditional compilation, header inclusion, macro operators (# and ##), predefined macros, multi-line and variadic macros, include guards, and best practices.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

C's preprocessor lets you control what code gets compiled, name constants, and write short templates that expand into code. Engineers use it to make code portable across platforms, turn debugging on/off, and avoid repeating code.

Key ideas

  • Macro: A macro is a name that the preprocessor replaces with its replacement text. There are two main types:
    • Object-like macro: A simple name that stands for a replacement text, often used as a constant substitute.
    • Function-like macro: A macro that looks like a function call with parameters; on expansion, the parameters are substituted into the replacement text.
  • Macro expansion: Macro expansion is the textual substitution performed by the preprocessor, not by the compiler. It happens before type checking and before actual compilation. No run-time cost is added directly by expansion.
  • Header inclusion: The #include directive copies the contents of a header file at that point. It supports two forms: angle brackets <...> for system headers and double quotes "..." for user headers (with different search rules).
  • Conditional compilation: Conditional compilation lets you compile parts of the program depending on conditions. Directives like #if, #ifdef, #ifndef, #elif, #else, and #endif include or exclude code during preprocessing based on constant expressions or macro definitions.
  • Include guard: An include guard is a pattern using #ifndef, #define, and #endif inside a header file to prevent the same header from being included multiple times.
  • Stringizing operator (#): In a function-like macro, # before a parameter name converts the argument into a string literal during expansion.
  • Token-pasting operator (##): In a function-like macro, ## pastes (concatenates) two tokens into a single token during expansion.
  • Variadic macro: A variadic macro accepts a variable number of arguments using ... and the identifier __VA_ARGS__ in the replacement list.
  • Predefined macros: The preprocessor provides built-in macros such as __FILE__ (current filename), __LINE__ (current line number), __DATE__ (date of compilation), __TIME__ (time of compilation), and __STDC__ (whether the compiler conforms to the C standard; nonzero in conforming modes). Also commonly used: __STDC_VERSION__ (a long integer like 201112L indicating the C standard version) and __STDC_HOSTED__ (1 for hosted implementations, 0 for freestanding).
  • Parenthesize macro parameters: Best practice is to wrap every parameter and the whole replacement in parentheses to avoid precedence errors.
  • Side effects in macros: Because macro parameters are substituted textually and may appear multiple times, using expressions with side effects (like i++) as macro arguments can cause multiple evaluations and undefined behavior. Avoid side-effect expressions as macro arguments.
  • Multi-line macros: A macro can span multiple lines using a backslash \ at the end of each continued line. A standard idiom uses do { ... } while (0) to make a safe single-statement block.
  • Difference between macros and functions: Macros are expanded by the preprocessor with no type checking and possible multiple evaluation of arguments; functions are compiled, type-checked, and evaluate arguments exactly once. For many cases, const, enum, and inline functions (e.g., static inline), and C11 generic selections (_Generic) are safer than macros.

Exact statements commonly examined:

  1. Definition: An object-like macro is defined by #define identifier replacement-list and each occurrence of identifier in subsequent code (outside strings and character constants) is replaced by replacement-list during preprocessing.
  2. Definition: A function-like macro is defined by #define identifier(parameter-list) replacement-list. On expansion, each parameter in replacement-list is replaced by the corresponding argument tokens, then normal macro rescanning rules apply.
  3. Law: In conditional compilation, the #if expression is evaluated using integer constant expression rules of the preprocessor after macro replacement. Nonzero is treated as true; zero is false.
  4. Rule: #include <header.h> searches implementation-defined system include paths; #include "header.h" first searches the directory of the current file, then falls back to system paths.
  5. Rule: #undef identifier cancels any previous macro definition of identifier from that point forward.
  6. Pattern (include guard): Place at top of a header file: #ifndef HEADER_NAME_H then #define HEADER_NAME_H and end with #endif to prevent multiple inclusion.

What diagram to draw (if asked "Explain preprocessing flow"):

  • Draw a left-to-right block diagram with these labeled boxes and arrows:
    1. Box: "Source files (.c) + Header files (.h)" → arrow labeled "feeding into preprocessor" →
    2. Box: "Preprocessor (handles #include, #define, #if...)" → arrow labeled "produces" →
    3. Box: "Expanded translation unit (.i)" → arrow labeled "to compiler" →
    4. Box: "Compiler → Object code (.o)".
  • Under the preprocessor box, list: macro expansion, file inclusion, conditional compilation.

Formulas

  • Meaning: Define object-like macro NAME to expand to replacement. Applies from this line onward in the file (and after inclusion) until #undef or end of translation unit.
  • #define NAME(params) replacement
    • Meaning: Define function-like macro NAME with parameters, expanding replacement with parameters substituted. Use parentheses to avoid precedence issues.
  • #undef NAME
    • Meaning: Undefine the macro NAME; further uses are not expanded.
  • #include <header.h>
    • Meaning: Include a system or standard library header; searched in implementation-defined system include paths.
  • #include "header.h"
    • Meaning: Include a user header; searched first in the current file’s directory, then in system paths.
  • #if constant-expression
    • Meaning: If the expression (after macro replacement) is nonzero, the following block is included. Use the defined(NAME) or defined NAME operator to test whether a macro is defined inside an #if.
  • #ifdef NAME
    • Meaning: True if NAME is defined as a macro.
  • #ifndef NAME
    • Meaning: True if NAME is not defined as a macro.
  • #elif constant-expression
    • Meaning: Else-if branch in conditional compilation.
  • #else
    • Meaning: Final else branch in conditional compilation.
  • #endif
    • Meaning: Ends a conditional compilation block.
  • #error message
    • Meaning: Generate a compilation error with the given message during preprocessing.
  • #pragma directive
    • Meaning: Implementation-defined directive to control compiler behavior (use with care; not portable).
  • #define LOG(fmt, ...) printf(fmt, __VA_ARGS__)
    • Meaning: Variadic macro that forwards a variable number of arguments to printf.
  • #define STR(x) #x
    • Meaning: Stringizing macro: converts the argument tokens for x into a string literal.
  • #define CAT(a, b) a##b
    • Meaning: Token-pasting macro: concatenates tokens a and b into a single token.
  • #ifndef HEADER_H #define HEADER_H ... declarations ... #endif
    • Meaning: Include guard pattern to prevent multiple inclusion of header contents.

Worked examples

Example 1 — Object-like and function-like macros with safe parentheses

Complete program:

#include <stdio.h>

#define PI 3.14159265358979323846
#define SQUARE(x) ((x) * (x))
#define CIRC_AREA(r) (PI * (r) * (r))

int main(void) {
    double r = 2.5; // radius in metres (for example)
    int a = 7;

    printf("PI = %.6f\n", PI);
    printf("SQUARE(%d) = %d\n", a, SQUARE(a));
    printf("CIRC_AREA(%.2f) = %.4f\n", r, CIRC_AREA(r));
    printf("SQUARE(3+2) = %d\n", SQUARE(3 + 2));
    return 0;
}

Sample input: (none)

Exact output:

PI = 3.141593
SQUARE(7) = 49
CIRC_AREA(2.50) = 19.6350
SQUARE(3+2) = 25

Notes: SQUARE(3+2) works correctly because we used parentheses around parameters and the whole expression.

Example 2 — Conditional compilation for debugging

Complete program:

#include <stdio.h>

#define DEBUG 1

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 3; i++) {
        sum += i;
#ifdef DEBUG
        printf("i=%d, sum=%d\n", i, sum);
#endif
    }
    printf("Final sum=%d\n", sum);
    return 0;
}

Sample input: (none)

Exact output when DEBUG is defined:

i=1, sum=1
i=2, sum=3
i=3, sum=6
Final sum=6

If you comment out #define DEBUG 1, the output will be:

Final sum=6

Example 3 — Stringizing and token pasting

Complete program:

#include <stdio.h>

#define LOG_INT(var) printf(#var " = %d\n", (var))
#define MAKE_ID(a, b) a##b

int main(void) {
    int x1 = 10;
    int MAKE_ID(x, 2) = 20; // becomes int x2 = 20;

    LOG_INT(x1); // prints: x1 = 10
    LOG_INT(x2); // prints: x2 = 20
    return 0;
}

Sample input: (none)

Exact output:

x1 = 10
x2 = 20

(Optional pattern to learn — multi-line macro for swap using do-while(0)):

  • Syntax to memorize, not a separate runnable program here:
#define SWAP_INT(a, b) do { int _t = (a); (a) = (b); (b) = _t; } while (0)
  • Safe as a single statement and avoids surprises when used in if statements without braces.

Common mistakes

  • Trailing semicolon in macro definition: #define M() do_something(); used as M(); becomes do_something();;. While usually harmless, with if-else it can misbehave. Prefer do { ... } while (0) pattern for block-like macros.
  • Missing backslash in multi-line macro: Without \ at end of line, the macro ends early and the next line becomes normal code, often causing compilation errors.
  • Using #include "..." vs <...> incorrectly: For user headers in the same project, prefer "..." so the current directory is searched first. For standard library headers, use <...>.
  • No include guards in headers: Multiple inclusion creates redefinition errors. Always wrap headers with #ifndef/#define/#endif.
  • Overusing macros instead of safer constructs: Use const variables, enum for integral constants, and static inline functions for typed, single-evaluation behavior where possible.
  • Assuming macros are scoped like variables: Macro definitions are active from the point of definition to the end of the translation unit (or until #undef), regardless of C block scopes.
  • Stringizing and token pasting misuse: Forgetting that # and ## only work on macro parameters inside function-like macros; using them in object-like macros will not work.
  • Not understanding header search paths on different systems: Build failures occur if include directories (-I flags) are not set properly for user headers.

For your exam

  • Diagrams: Preprocessing workflow diagram with labels as described in Key ideas.
  • Programs: Write small programs using #define macros; demonstrate conditional compilation (#ifdef DEBUG); demonstrate stringizing # and token-pasting ## with simple variables; ensure programs compile and run without undefined behavior.
  • Best-practice points for full marks: Always show parentheses in macro definitions; avoid side-effect arguments; show include guard template; mention that preprocessor runs before compilation; mention search order difference between <...> and "...".
  • Common theory questions: Explain conditional compilation with an example; explain why macros can be dangerous; explain include guards; list and explain predefined macros; explain # and ## operators with examples.

Quick check

  1. Why must function-like macro parameters be wrapped in parentheses in the replacement text?
  2. What is the difference between #include <stdio.h> and #include "myhdr.h"?
  3. Write a one-line variadic macro LOG that prints a formatted message by calling printf.

Answers: 1) To ensure correct operator precedence and grouping so expressions like 3+2 are treated as a single unit and evaluated as intended. 2) Angle brackets search system include paths; double quotes search the including file’s directory first, then system paths. 3) #define LOG(fmt, ...) printf((fmt), __VA_ARGS__).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?