The Preprocessor

suggest change

Preprocessing is an early phase of translating a C source file. It handles directives, expands macros, processes included files, removes comments, and evaluates conditional-compilation directives. Its output consists of preprocessing tokens that later translation phases parse as C.

Preprocessing directives begin with # after optional whitespace at the start of a logical source line.

Object-like Macros

#define MAX_RECORDS 1000

int records[MAX_RECORDS];

The preprocessor replaces uses of MAX_RECORDS with its replacement list. Macros are useful where the language requires preprocessing, but typed language features such as enumerations, const objects, and inline functions are often clearer when they meet the same need.

Function-like Macros

#define SQUARE(value) ((value) * (value))

Function-like macros do not provide ordinary function type checking, and their arguments can be evaluated more than once. For example, SQUARE(i++) has undefined behavior because it modifies i more than once without sequencing. Parenthesize macro parameters and the complete replacement expression, avoid side effects in arguments, and prefer an inline function when possible.

For a multi-statement macro, the do { ... } while (0) pattern makes the expansion behave like one statement:

#define SET_TRUE(value)  \
    do {                 \
        (value) = 1;     \
    } while (0)

File Inclusion

#include <stdio.h>
#include "project.h"

An #include directive causes the named header to be processed as part of the translation unit. Angle brackets normally search implementation-defined system locations; quotes normally search relative to the including file first and then use an implementation-defined search.

Headers typically provide declarations, type definitions, and macros. Including <stdio.h>, for example, declares standard I/O functions such as printf. Modern C requires a function to be declared before a call whose definition is not already visible.

Conditional Compilation

#if defined(PLATFORM_A) || defined(PLATFORM_B)
    value = source + 1;
#else
    value = source * 2;
#endif

Only the selected group of preprocessing tokens continues to later translation phases. Conditional compilation is commonly used for platform-specific code, optional features, include guards, and configuration checks. Prefer project-owned feature macros over guesses based on compiler or operating-system macros.

Comments

/* ... */ comments are replaced with a single space during translation. // comments extend to the next newline. Because comments are removed before macro expansion, they cannot be created by expanding a macro.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents