< Previous | Contents | Next >

Using Global Constants

Unlike global variables, which can make your programs confusing, global constantsconstants that can be accessed from anywhere in your programcan help make programs clearer. You declare a global constant much like you declare a global variableby declaring it outside of any function. And because

youre 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

image

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.

image


How exactly can global constants make game programming code clearer? Well, suppose youre 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 thats 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