Developer knowledge network · moderated exchange

UnreliableCode Topluluğu

Geliştirici Araştırması, Tersine Mühendislik ve Kodlama Topluluğu

Knowledge indexCanlı
4Categories
919Threads
2.8KGönderiler
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
Temsilci: 190
Katılım Tarihi: Aug 2020
Gönderiler: 20
Teşekkürler: 22
1 ay önce · 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
Temsilci: 124
Katılım Tarihi: Jun 2019
Gönderiler: 29
Teşekkürler: 72
1 ay önce · 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
Temsilci: 139
Katılım Tarihi: Jul 2018
Gönderiler: 21
Teşekkürler: 15
1 ay önce · Jul 18, 2026 3:41 PM
#3

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