Discussion
Team LiB
Previous Section Next Section

Discussion

It's hard to find language that's colorful enough to describe macros, but we'll try. To quote from [Sutter04] §31:

Macros are obnoxious, smelly, sheet-hogging bedfellows for several reasons, most of which are related to the fact that they are a glorified text-substitution facility whose effects are applied during preprocessing, before any C++ syntax and semantic rules can even begin to apply.

Lest there remain any ambiguity on this point, we note also that Bjarne Stroustrup has written:

I dislike most forms of preprocessors and macros. One of C++'s aims is to make C's preprocessor redundant (§4.4, §18) because I consider its actions inherently error prone.

[Stroustrup94] §3.3.1

Macros are almost never necessary in C++. Use const (§5.4) or enum (§4.8) to define manifest constants [see Item 15], inline (§7.1.1) to avoid function-calling overhead [but see Item 8], templates (Chapter 13) to specify families of functions and types [see Items 64 through 67], and namespaces (§8.2) to avoid name clashes [see Items 57 through 59].

[Stroustrup00] §1.6.1

The first rule about macros is: Don't use them unless you have to. Almost every macro demonstrates a flaw in the programming language, in the program, or in the programmer.

[Stroustrup00] §7.8

The main problem with C++ macros is that they seem much better at what they do than they really are. Macros ignore scopes, ignore the type system, ignore all other language features and rules, and hijack the symbols they #define for the remainder of a file. Macro invocations look like symbols or function calls, but are neither. Macros are not "hygienic," meaning that they can expand to significantly and surprisingly different things depending on the context in which they are used. The text substitution that macros perform makes writing even remotely proper macros a black art whose mastery is as unrewarding as it is tedious.

People who think that template-related errors are the worst to decipher probably haven't seen those caused by badly formed or badly used macros. Templates are part of C++'s type system and thus allow compilers to get better at handling them (which they do), whereas macros are forever divorced from the language and hence intractable. Worse, unlike a template, a macro might expand to some transmission line noise that undesirably compiles by pure chance. Finally, an error in a macro can only be reported after the macro is expanded and not when it is defined.

Even in the rare cases where you do legitimately write a macro (see Exceptions), never ever even consider starting to think about writing a macro that is a common word or abbreviation. Do #undefine macros as soon as possible, always give them SCREAMING_UPPERCASE_AND_UGLY names, and avoid putting them in headers.

    Team LiB
    Previous Section Next Section