liveBook · Manning

Preprocessor

As explained in 100 C++ Mistakes and How to Avoid Them

A preprocessor is a source-processing component that transforms code, including performing macro substitution, before compilation.

A preprocessor transforms source code before compilation. Its textual macro substitution can reduce repetitive typing, but it also means the compiler processes code different from what was written, complicating errors and debugging. section 5.2

Common macro mistakes include:

  • Using an untyped PI macro, which can produce an unintended type. section 5.2
  • Defining SQUARE(n) as n * n, which substitutes expressions repeatedly and can change results or evaluate side effects twice. section 5.2
  • Ending a FOR macro's loop header with a semicolon, creating a null loop body and leaving the following statement to run once. section 5.2

Replace macros with C++ constructs

Use a typed const double for PI, a template function for square, an explicit for loop, and bool with false rather than value-like macros. These forms make the generated behavior visible and prevent accidental repeated substitution.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains textual substitution through concrete failures and contrasts macros with typed constants, templates, loops, and bool.
Examples
Uses PI, SQUARE, FOR, TRUE, and FALSE macros alongside corrected C++ equivalents.
What it assumes
Assumes basic C++ expressions, loops, functions, and types while illustrating their safer use from concrete macro mistakes.
What you can do after
Evaluate macro hazards and replace simple macros with typed constants, template functions, explicit loops, and bool values.
How it connects
Connects the preprocessor with macros, compilation, debugging, templates, loops, and boolean types.

Also explained in

Compare how 3 books explain preprocessor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.