Game Development Reference
In-Depth Information
Constant Variables
Constant variables are used to avoid having magic numbers in our code and to generally represent
values that we know at compile time and will never change during execution. Classic examples in
game programming are constant values used to represent pi or the values used to convert angles in
degrees to angles in radians and vice versa. Listing 9-12 shows how we can create some constant
variables to reference in our code.
Listing 9-12. Example Constant Variables
#include "stdafx.h"
#include <iostream>
#include "extern.h"
int globalVariable = 0;
namespace
{
const unsigned int MAX_LOOPS = 10;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (unsigned int i = 0; i < MAX_LOOPS; ++i)
{
IncrementGlobalCounters();
std::cout << globalVariable << std::endl;
}
}
We have added a const unsigned int variable named MAX_LOOPS to our code from Listing 9-11. The
benefit of using a constant is that if you use the same variable in multiple places, you would only
have to change the value in a single place to ensure that the value is changed everywhere it is used.
You can see this benefit in Listing 9-13.
Listing 9-13. Using a const Variable in Multiple Places
unsigned int arrayOfValues[MAX_LOOPS];
for (unsigned int i = 0; i < MAX_LOOPS; ++i)
{
arrayOfValues[i] = i;
IncrementGlobalCounters();
std::cout << globalVariable << std::endl;
std::cout << fileVariable << std::endl;
}
If you fail to use a constant variable and instead use the value 10 in the array definition and in the
loop, you run the risk of introducing bugs. If the array was reduced to contain 5 elements and the
loop remained at 10 then the loop would overrun the end of the array and overwrite memory used to
store values in other variables.
 
Search WWH ::




Custom Search