Most applications will use particular values throughout the code. Imagine an application which does a lot of calculations with circles: you will definitely use the number pi a lot. You could calculate pi every time you need it, but that’s not a good idea because the outcome will be the same every time. You’re making your computer do needless calculations. Instead you could declare a global variable:
int pi = 3.1415926;
With this variable, you can use pi everywhere in your code. But mistakes happen, and what about this one:
int value = 1;
// ... more code ...
if(pi = value) {
// do something
5}
The code above won’t result in an error. But instead of comparing pi, you assign a new value to pi by mistake. Auch! This mistake is easily made, but it might take a while before you realize why every calculation with pi suddenly has the wrong outcome.
It would be much better if we could prevent such a mistake from being made. After assigning a value to pi, there is no reason why it should change. We need a way to prevent changes made to this variable. That’s why most programming languages provide a way to make a variable ‘constant’. A constant can never changes after its declaration. And to increase readability, most programmers will always write constants in capitals.
So how do you declare a constant in C++? You precede it with the word const. Esenthel makes it even easier by defining the capital C as const, just like you can write T instead of this. In Esenthel, you could declare PI as:
C PI = 3.1415926;
This approach has two advantages: