Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

conventions - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...