This Item might better be called “prefer the compiler to the preprocessor,” because #define may be treated as if it’s not part of the language per se. That’s one of its problems. When you do something like this,
- #define ASPECT_RATIO 1.653
the symbolic name ASPECT_RATIO may never be seen by compilers; it may be removed by the preprocessor before the source code ever gets to a compiler. As a result, the name ASPECT_RATIO may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 1.653, not ASPECT_RATIO. If ASPECT_RATIO were defined in a header file you didn’t write, you’d have no idea where that 1.653 came from, and you’d waste time tracking it down. This problem can also crop up in a symbolic debugger, because, again, the name you’re programming with may not be in the symbol table.
The solution is to replace the macro with a constant:
- const double AspectRatio = 1.653;
-
As a language constant, AspectRatio is definitely seen by compilers and is certainly entered into their symbol tables. In addition, in the case of a floating point constant (such as in this example), use of the constant may yield smaller code than using a #define. That’s because the preprocessor’s blind substitution of the macro name ASPECT_RATIO with 1.653 could result in multiple copies of 1.653 in your object code, while the use of the constant AspectRatio should never result in more than one copy.
C++(www.cppentry.com)强调强类型,这可以帮助程序员从纷纷扰扰、乱花迷人眼的语法糖陷阱中解脱出来,帮助编译器自动发现程序员的错误。而C语言的哲学则是可显性,推荐程序“表里如一”。C语言虽然类型较弱,但尽可能地把实际工作展现出来。在大多数情况下,宏在语言中起到的作用是使程序更易读、可配置,而并非改变语言的表现形式,或是提供一种DSL(领域相关语言)。