What does the C++ preprocessor do, and when should macros be replaced with constexpr values, inline functions, templates, or scoped constants?
Show answer and explanation
Preprocessing handles directives such as file inclusion, conditional inclusion, macro definition and expansion, stringizing, and token pasting before normal C++ parsing and semantic analysis. A macro is token substitution: it has no C++ type or namespace scope, its arguments may be expanded more than once, and generated tokens can interact unexpectedly with precedence or surrounding names. Prefer inline constexpr variables for named constants, inline or constexpr functions for evaluated behavior, and templates for type-generic behavior because those alternatives participate in type checking, scope, overload resolution, and debugging. Macros remain appropriate for conditional compilation, feature or platform probes, include guards, and narrowly controlled source-generation tasks. When a function-like macro is unavoidable, parenthesize parameters and the result, avoid side-effecting arguments, choose collision-resistant names, and keep the macro's lifetime as short as practical.
Preprocessing handles directives such as file inclusion, conditional inclusion, macro definition and expansion, stringizing, and token pasting before normal C++ parsing and semantic analysis. A macro is token substitution: it has no C++ type or namespace scope, its arguments may be expanded more than once, and generated tokens can interact unexpectedly with precedence or surrounding names. Prefer inline constexpr variables for named constants, inline or constexpr functions for evaluated behavior, and templates for type-generic behavior because those alternatives participate in type checking, scope, overload resolution, and debugging. Macros remain appropriate for conditional compilation, feature or platform probes, include guards, and narrowly controlled source-generation tasks. When a function-like macro is unavoidable, parenthesize parameters and the result, avoid side-effecting arguments, choose collision-resistant names, and keep the macro's lifetime as short as practical.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.