The Preprocessor & Macros in C++
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.
Textual substitution
#define PI 3.14 replaces the token PI everywhere before compiling — no type, no scope, no mercy.
Guard every header
#pragma once (or classic #ifndef guards) makes double-inclusion impossible — redefinition errors vanish.
Conditional compilation
#ifdef _WIN32 ... #else ... #endif compiles different code per platform or build flag — the portable-code workhorse.
Prefer real language
constexpr doubles as typed constants, inline variables replace globals, templates replace generic macros — reach for macros last.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.