< Previous | Contents | Next >
Unlike global variables, which can make your programs confusing, global constants—constants that can be accessed from anywhere in your program— can help make programs clearer. You declare a global constant much like you declare a global variable—by declaring it outside of any function. And because
you’re declaring a constant, you need to use the const keyword. For example, the following line defines a global constant (assuming the declaration is outside of any function) named MAX_ENEMIES with a value of 10 that can be accessed anywhere in the program.
const int MAX_ENEMIES = 10;
Tra p
Just like with global variables, you can hide a global constant by declaring a local constant with the same name. However, you should avoid this because it can lead to confusion.
How exactly can global constants make game programming code clearer? Well, suppose you’re writing an action game in which you want to limit the total number of enemies that can blast the poor player at once. Instead of using a numeric literal everywhere, such as 10, you could define a global constant MAX_ENEMIES that’s equal to 10. Then whenever you see that global constant name, you know exactly what it stands for.
One caveat: You should only use global constants if you need a constant value in more than one part of your program. If you only need a constant value in a specific scope (such as in a single function), use a local constant instead.
Using Default Arguments 171