Learn C++
#include "advanced/preprocessor.hpp"

The Preprocessor & Macros in C++

//concept

Before compiling, the preprocessor textually processes # directives: #include pastes files, #define stamps macros, #ifdef/#ifndef/#endif compile conditionally. Include guards (#ifndef HEADER_H / #define / #endif, or #pragma once) stop headers from being pasted twice and breaking builds.

Function-like macros (#define SQUARE(x) ((x)*(x))) are textual substitution — fast but untyped, unevaluated-multiple-times dangerous, and invisible to debuggers. Modern C++ replaces them with constexpr functions, inline variables, and templates; macros survive for conditional compilation, logging (__FILE__, __LINE__), and legacy interfaces.

//how it works
1

Textual substitution

#define PI 3.14 replaces the token PI everywhere before compiling — no type, no scope, no mercy.

2

Guard every header

#pragma once (or classic #ifndef guards) makes double-inclusion impossible — redefinition errors vanish.

3

Conditional compilation

#ifdef _WIN32 ... #else ... #endif compiles different code per platform or build flag — the portable-code workhorse.

4

Prefer real language

constexpr doubles as typed constants, inline variables replace globals, templates replace generic macros — reach for macros last.

//example
#include <iostream>
 
#define SQUARE(x) ((x) * (x))
constexpr int csquare(int x) { return x * x; }
 
int main() {
std::cout << SQUARE(3 + 1) << ", " << csquare(3 + 1) << std::endl;
return 0;
}
Output
16, 16
1The macro pastes ((3 + 1) * (3 + 1)) — the inner parentheses (which novices omit) save it from expanding to 3 + 1 * 3 + 1 = 7.
2The constexpr function computes the same 16 with real parameters, types, and debugger visibility.
3Both print 16 here, but only the function is safe by construction — the macro merely survived its parentheses.
//use cases
Platform branches (#ifdef _WIN32) in portable libraries
Header guards making multiple inclusion harmless
Debug logging macros capturing __FILE__ and __LINE__ automatically
Migrating legacy macros to constexpr/inline equivalents

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.