13.1 Global Constants

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:

  1. The value of PI can never be changed by mistake.
  2. If, for some crazy reason, you need to change the value of PI, you only have to change it this one instance. (Highly unlikely in this case, but it will happen with other constant values in your application. Imagine a constant named ATTACK_RANGE. You probably will want to experiment with that before releasing your game.)

Note
Because PI is needed in almost every game, Esenthel already declared it for you. And not only PI is defined, but also a few common calculations like PI_2 (half of PI) and PI2 (two times PI).

Exercise
Write an application with the following constants: playerColor, playerSize, enemyColor and enemySize. The player is a rectangle, the enemies are circles (it is a very abstract game). Draw a player and some enemies on the screen using these constants.