简体   繁体   English

使用常量而不是数字 - c

[英]Using constants instead of numbers - c

I'm currently learning c, and our teacher told us we should never use plain numbers in code, and always use constants.我目前正在学习 c,我们的老师告诉我们,我们不应该在代码中使用纯数字,并且始终使用常量。

For example:例如:

Don't do this:不要这样做:

if (age >= 18) {...}

Do this:做这个:

#define MIN_AGE 18
// ...
if (age >= MIN_AGE) {...}

They did not give us any reasoning for why to do this, and I'm left confused.他们没有给我们任何理由说明为什么要这样做,我很困惑。 Is this actually recommended?这真的推荐吗? And why?为什么?

The reason to use variables is that is much easier for maintenance and visualization.使用变量的原因是更容易维护和可视化。 In the code without the variable that you showed, you would not have much of a problem changing the value directly in the if statement because you're using it only once.在没有您显示的变量的代码中,直接在if语句中更改值不会有太大问题,因为您只使用了一次。

if (age >= 18) {...}

So if you need to change the value to 17 (as an example) you could just do this:因此,如果您需要将值更改为 17(例如),您可以这样做:

if (age >= 17) {...}

But imagine if you had a lot more if statements in your code, like in the example below:但是想象一下,如果您的代码中有更多if语句,如下例所示:

if (age >= 18) {...}
if (age >= 18) {...}
if (age >= 18) {...}

You would need to change it in every statement, one by one.您需要在每个语句中逐个更改它。 Using a variable would be a lot easier because you could just change the value assigned to the variable:使用变量会容易得多,因为您可以更改分配给变量的值:

#define MIN_AGE 17

And all the other MIN_AGE variables would be already correct:并且所有其他MIN_AGE变量都已经正确:

if (age >= MIN_AGE) {...}
if (age >= MIN_AGE) {...}
if (age >= MIN_AGE) {...}

Besides, that is a lot easier to understand the meaning of MIN_AGE , the code will better to read and understand.此外,这更容易理解MIN_AGE的含义,代码将更好地阅读和理解。

Sorry for my bad English btw!对不起,我的英语不好顺便说一句!

The purpose of this is to give names to variables.这样做的目的是为变量命名。 Why is 18 special?为什么18很特别? If we're talking about buying alcohol in the US we might have a macro:如果我们谈论在美国购买酒精,我们可能会有一个宏观:

#define MIN_AGE_TO_PURCHASE_ALCOHOL 18

That string is far easier for the programmer to understand than just 18. Especially when you continue to support this code 10 years later.对于程序员来说,这个字符串比 18 更容易理解。尤其是当你在 10 年后继续支持这个代码时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM