什么是“符号常数”?和“魔术常数”?

编程入门 行业动态 更新时间:2024-10-26 06:33:55
本文介绍了什么是“符号常数”?和“魔术常数”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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.

更多推荐

什么是“符号常数”?和“魔术常数”?

本文发布于:2023-08-01 08:56:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常数   魔术   符号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!