Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
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
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
1 miesięcy temu · 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
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
1 miesięcy temu · 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
Rozpustnik: 139
Data dołączenia: Jul 2018
Posty: 21
Dzięki: 15
1 miesięcy temu · Jul 18, 2026 3:41 PM
#3

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