Reputation: 178
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?
Upvotes: 1
Views: 701
Reputation: 445
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, it's a lot easier to understand the meaning of MIN_AGE
, the code will better to read and understand.
Sorry for my bad English btw!
Upvotes: 4
Reputation: 81926
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.
Upvotes: 0