Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Guide

Why you should avoid C-style macros in Modern C++ and use constexpr, inline variables, and templates [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Vertreter: 190
Beitrittsdatum: Aug 2020
Beiträge: 20
Danke: 22
Vor 1 Monaten · Jul 18, 2026 3:01 AM
#1

Why preprocessor #define macros are error-prone and what to replace them with:

  • Problem: Macros ignore scope, pollute global namespace, cause multiple evaluation side-effects (#define SQUARE(x) (x*x) with SQUARE(i++)), and produce cryptic compiler errors.

Modern C++ Replacements:

  • Constants: constexpr int MaxRetries = 5;
  • Global flags: inline constexpr std::string_view Version = "2.4.0";
  • Utility functions: template<typename T> constexpr T Square(T x) { return x * x; }
  • Compile-time conditions: if constexpr (sizeof(T) == 8) instead of #ifdef _WIN64.
modern_cpp_artisan
C++ Template Wizard
MEMBER
Vertreter: 124
Beitrittsdatum: Jun 2019
Beiträge: 29
Danke: 72
Vor 1 Monaten · Jul 18, 2026 5:11 AM
#2

Macros should be restricted strictly to header guards, conditional feature platform detection, and specialized stringification #x macros.

llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
Vertreter: 139
Beitrittsdatum: Jul 2018
Beiträge: 21
Danke: 15
Vor 1 Monaten · Jul 18, 2026 3:41 PM
#3

Everything else can and should be expressed using type-safe Modern C++ constructs.