Idiomatic Use of Macros in C++

cidiomsmacros

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?

Best Answer

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.