Macros are considered a good thing by one and evil by another.
Is there a rule of thumb when to and when not to use macros in C++?
When are macros idiomatic and when should they be avoided?
Macros are considered a good thing by one and evil by another.
Is there a rule of thumb when to and when not to use macros in C++?
When are macros idiomatic and when should they be avoided?
As a rule, you should only use macros, when a better alternative does not exist.
They should not be used to generate code; you should simply write the code instead (if the code is type-agnostic, write a template instead).
They should not be used to define constants; constants should be defined using one of these: (static) constexpr/const variables, anonymous enumerations, named enumerations, enum classes (depending on what you want to use them for).
They should be used for conditional compilation (include guards are one of these cases).
Ideally, they should not be used to conditionally change the API of a module at compilation (that is, ideally you should declare the same functions in all configurations, then use conditional compilation in the implementation file.
In all* other cases, macros should be avoided.
(*) - Sometimes, there are exceptions to "all other cases" (for example, you may have third party code that requires you to use macros; that's life :-) ).
When are macros idiomatic and when should they be avoided?
Macros are idiomatic only when there is no alternative to their use. Examples are include guards (they are the only portable form), embedded domain-specific languages, special compiler support not available through other language features (embedding built-in macros like __FILE__
, stringifying and concatenating identifiers), and a few other places.
Macros should be avoided whenever possible. That's because they follow their own very simplistic syntax and know nothing about C++, dumbly trampling over any and all namespaces.
It has always been one of Stroustrup's goals to eliminate the preprocessor as much as possible. Function inlining, templates, and constants are a prime example, as are modules (to replace #include
), which have been chewed on by the standardization committee for years. The language features created to avoid having to use macros are all very much better than the macros they replace. Make use of them whenever possible.
The only time I'd consider macros are for compile time constants, typically ones that affect the compilation (as opposed to constant application values, which are better modelled as const types).
However, I have modelled utility routines such as calls to logging functions in a macro just so they will be compiled out, but I think even this is unnecessary today - the compiler should be clever enough to realise a logging function that does nothing due to conditional compilation will be optimised away, but old habits die hard :)