- Why would I use a constant instead of a variable?
- Beyond readability, is there another gain in using a constant?
I can not tell a difference that makes me use a constant instead of a variable.
I can not tell a difference that makes me use a constant instead of a variable.
I do not know if there is greater legibility. It is even considered that it best indicates the intention of the value to be constant.
The constant, provided it is constant even, has the advantage of protection, any attempt to write to it will not work. If it's what you want, then it's interesting that the compiler helps with this.
Note that it is very common to call variables that read only constant. If the value is determined at runtime it is not a classical constant, it is a variable that can not have its value changed, it can only be initialized.
There are other contexts where the term constant does not always mean constant. There is transitory constancy, which seems a contradiction at least to name this constant mechanism. So at some point the variable should keep its value constant, but we're still talking about a variable.
It has a language that calls a constant that is not even allowed to change the value. Run away.
Imutability is something good, constancy is an immutability taken to the extreme. But abusing immutability can be harmful. Has design pattern that uses immutability to simplify the use of constants .
Constant can be better optimized and use its direct value instead of having an indirection that every variable has . Not all languages do this.
If the data can not change, why not guarantee this and prevent accidents? So whenever this is your situation you prefer constant. It may even cause fewer problems one day to have to make the constant a variable, rather than the other. But you can still have problems if there is a presumption that that value will never change. So it is very useful, just not fundamental. You can trust conventions, but I would not do that.