0 Preface
魔法数字:通常是在计算机编程领域。
魔法数字的缺点:
- 可读性差(单个数字,不知道具体含义)
- 维护性差(可能需要修改多个地方)
1 介绍
Magic number:魔法数字,常在软件编程中可以看到,具体是指,该数字在程序源代码中,但是不知道该数字的含义和作用,即可读性很差。
例如:
int main(int argc, char *argv[])
{
int ret = 0;
int total = 0
total = 10 * 10;
printf("total fee is %d\n", total);
}
上面的10 * 10,根本不知道代表的含义。这两个数字10都可以称为Magic Number。
消除魔法数字:
#define PRICE (10)
#define AMOUNT (10)
int main(int argc, char *argv[])
{
int ret = 0;
int total = 0
total = PRICE * AMOUNT;
printf("total fee is %d\n", total);
}