Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
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
Vertegenwoordiger: 190
Datum van deelname: Aug 2020
Berichten: 20
Bedankt: 22
1 maanden geleden ยท 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
Vertegenwoordiger: 124
Datum van deelname: Jun 2019
Berichten: 29
Bedankt: 72
1 maanden geleden ยท 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
Vertegenwoordiger: 139
Datum van deelname: Jul 2018
Berichten: 21
Bedankt: 15
1 maanden geleden ยท Jul 18, 2026 3:41 PM
#3

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