< previous page page_370 next page >

Page 370
DODON'T
DO use uppercase for your macro names. This is a pervasive convention, and other programmers will be confused if you don't.DON'T allow your macros to have side effects. Don't increment variables or assign values from within a macro.
DO surround all arguments with parentheses in macro functions.

Summary
In this hour you learned more details about working with the preprocessor. Each time you run the compiler, the preprocessor runs first and translates your preprocessor directives such as #define and #ifdef.
The preprocessor does text substitution, although. with the use of macros. these can be somewhat complex. By using #ifdef, #else, and #ifndef, you can accomplish conditional compilation, compiling in some statements under one set of conditions and in another set of statements under other conditions. This can assist in writing programs for more than one platform, and is often used to conditionally include debugging information.
Macro functions provide complex text substitution based on arguments passed at compile time to the macro. It is important to put parentheses around every argument in the macro to ensure that the correct substitution takes place.
Macro functions, and the preprocessor in general, are less important in C++ than they were in C. C++ provides a number of language features, such as const variables and templates, that offer superior alternatives to using the preprocessor.
Q&A
Q If C++ offers better alternatives than the preprocessor, why is this option still available?
A First, C++ is backward compatible with C, and all significant parts of C must be supported in C++. Second, there are some uses of the preprocessor that are still employed frequently in C++, such as inclusion guards.
Q Why use macro functions when you can use a regular function?
A Macro functions are expanded inline and are used as a substitute for repeatedly typing the same commands with minor variations. However, templates offer a better alternative.

 
< previous page page_370 next page >

If you like this book, buy it!