[Solved] Why are constants used instead of variables?


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.

3

solved Why are constants used instead of variables?