简体   繁体   中英

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.

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 (age >= 18) {...}

So if you need to change the value to 17 (as an example) you could just do this:

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

But imagine if you had a lot more if statements in your code, like in the example below:

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:

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.

Sorry for my bad English btw!

The purpose of this is to give names to variables. Why is 18 special? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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