Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
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
Rep: 190
Datum pridruživanja: Aug 2020
Postovi: 20
Hvala: 22
prije 1 mjeseci · 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
Rep: 124
Datum pridruživanja: Jun 2019
Postovi: 29
Hvala: 72
prije 1 mjeseci · 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
Rep: 139
Datum pridruživanja: Jul 2018
Postovi: 21
Hvala: 15
prije 1 mjeseci · Jul 18, 2026 3:41 PM
#3

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