什么是“幻数"?在计算机编程中? [英] What are "magic numbers" in computer programming?

查看:605
本文介绍了什么是“幻数"?在计算机编程中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当人们谈论在计算机编程中使用幻数"时,它们是什么意思?

When people talk about the use of "magic numbers" in computer programming, what do they mean?

推荐答案

魔术数字是代码中任何对知识很少的人都不是立即可见的数字.

Magic numbers are any number in your code that isn't immediately obvious to someone with very little knowledge.

例如,以下代码:

sz = sz + 729;

其中有一个魔术数字,最好写成:

has a magic number in it and would be far better written as:

sz = sz + CAPACITY_INCREMENT;

一些极端的观点指出,除了-1、0和1之外,您的代码中不应包含任何数字,但我更喜欢教条式的观点,因为我会立即识别出24、1440、86400、3.1415、2.71828和1.414-它一切都取决于您的知识.

Some extreme views state that you should never have any numbers in your code except -1, 0 and 1 but I prefer a somewhat less dogmatic view since I would instantly recognise 24, 1440, 86400, 3.1415, 2.71828 and 1.414 - it all depends on your knowledge.

但是,即使我知道一天中有1440分钟,我仍可能 still 使用MINS_PER_DAY标识符,因为它使搜索它们变得更加容易.谁说上面提到的容量增量也不会是1440,而您最终更改了错误的值?对于低数字尤其如此:双重使用37197的机会相对较低,将5用于多个事物的机会非常高.

However, even though I know there are 1440 minutes in a day, I would probably still use a MINS_PER_DAY identifier since it makes searching for them that much easier. Whose to say that the capacity increment mentioned above wouldn't also be 1440 and you end up changing the wrong value? This is especially true for the low numbers: the chance of dual use of 37197 is relatively low, the chance of using 5 for multiple things is pretty high.

使用标识符意味着您无需遍历所有700个源文件,并且在容量增量更改时将729更改为730.您可以只更改一行:

Use of an identifier means that you wouldn't have to go through all your 700 source files and change 729 to 730 when the capacity increment changed. You could just change the one line:

#define CAPACITY_INCREMENT 729

收件人:

#define CAPACITY_INCREMENT 730

然后重新编译很多.

将此与魔术常数进行对比,这是天真的人们认为仅仅因为他们从代码中删除了实际数字,他们就可以更改:

Contrast this with magic constants which are the result of naive people thinking that just because they remove the actual numbers from their code, they can change:

x = x + 4;

收件人:

#define FOUR 4
x = x + FOUR;

这绝对会在代码中添加个额外信息,这完全是浪费时间.

That adds absolutely zero extra information to your code and is a total waste of time.

这篇关于什么是“幻数"?在计算机编程中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆