User Centric Design with Big Data

The compiler is smarter than the preprocessor (Item 2)

The title of this entry in the book is “Prefer consts, enums and inlines to #defines”. As Dr. Meyers mentions this is just a more explicit way to say that you should use the power of the compiler whenever possible. So the practice of using #defines to create mathematical constants is just not a good idea. The preprocessor does not have to keep the name of the preprocessor definition; it can simply replace all occurrences with the defined value. This can make debugging harder. Also the preprocessor can make multiple copies of the constant that can add bloat to the compiled code. Therefore one should prefer the following:const double NatLogBase = 2.71828;to #define NAT_LOG_BASE 2.71828
This is pretty obvious stuff to many experienced C++ programmers. As mentioned in this item, class-scoped static constant integral-type declarations can also assign the variable in the header file. While it pains me to use this feature I do. I use this method rather than the “enum hack” mentioned below. This is needed for the declaration of arrays that have a symbolic constant as the size. Since enums can be used in place of ints it is common to define an enum in the header file of a class for the same reason. A simple example of this can be found here. Static const members were added to the language to replace the enum hack, but Dr. Meyers points out in Effective C++ that it is illegal to take the address of an enum, so this can allow more access control over how constants are used.I will not go into detail about preprocessor macros. They are crazy and should never be used. Use an inline function (possibly templated) instead since it is just as efficient and prevents bizarre side effects and does not require special spacing.