在Bjarne Stroustrup的C ++之旅中,每章的结尾列出了一些建议。在第一章的末尾,其中一个是:
In A Tour of C++ by Bjarne Stroustrup, some advice is listed at the end of each chapter. At the end of the first chapter one of them reads:
避免魔术常数;使用符号常数;
Avoid ‘‘magic constants;’’ use symbolic constants;
什么是魔术常数和符号常数?
What are magic and symbolic constants?
推荐答案somethingElse = something * 1440; // a magic constant somethingElse = something * TWIPS_PER_INCH; // a symbolic one
第一个是魔术常数的示例,它不传递任何其他信息
The first is an example of the magic constant, it conveys no other information other than its value.
后者更有用,因为其意图很明确。
The latter is far more useful since the intent is clear.
还使用符号常量
static const int TWIPS_PER_INCH = 1440; static const int SECTORS_PER_FLOPPY = 1440; // showing my age here :-)那样,如果一个其中有更改,您可以轻松确定代码中的哪个 1440 必须更改。在整个代码中散布着魔法 1440 的情况下,您必须在多个位置和进行更改,以找出哪些是缇,哪些是扇区。
That way, if one of them changes, you can easily identify which single 1440 in the code has to change. With magic 1440s scattered throughout the code, you have to change it in multiple places and figure out which are the twips and which are the sectors.
更多推荐
什么是“符号常数”?和“魔术常数”?
发布评论