Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Why are constants used instead of variables?

In what general occasions are constants used instead of variables. I need a few examples.

Thanks in advance.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

A variable, as the name implies, varies over time. Variables mostly allocate memory. In your code, when you declare that a value will not change, the compiler can do a series of optimizations (no space is allocated for constants on stack) and this is the foremost advantage of Constants.

Update

You may ask why do we use Constants after all?

It's a good question, actually, we can use literal numbers instead of constants. it does not make any difference for the compiler since it sees both the same. However, in order to have a more readable code (--programming good practice), we'd better use constants.

Using constants, you can also save your time!. To be more specific, take below as an example:

Suppose a rate value for some products in a shopping system (rate value = 8.14). Your system has worked with this constant for several months. But then after some months, you may want to change the rate value, right?. What are you going to do? You have one awful option! Changing all the literals numbers which equal 8.14! But when you declare rate as a constant you just need to change the constant value once and then changes will propagate all over the code. So you see that by using constants you do not need to find 8.14's (literal numbers) and change them one by one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...