Game Development Reference
In-Depth Information
Creating static Local Variables
The
static
local variable is the simplest version of
static
to understand. A normal local variable
will lose its value each time a function returns and will reset to the initialized value the next time the
function is called. Listing 9-1 shows an example of a normal local variable in action.
Listing 9-1. A Normal Local Variable
void NormalLocalVariable()
{
int x = 0;
std::cout << x++ << std::endl;
}
With the function source in Listing 9-1 the console will have the value 0 added every time we call the
function
NormalLocalVariable
. This is because the variable is re-created each time the function is
called. Listing 9-2 shows the code for a
static
local variable.
Listing 9-2. A
static
Local Variable
void StaticLocalVariable()
{
static int x = 0;
std::cout << x++ << std::endl;
}
This time you have told the compiler that you would like the variable
x
to be
static
. When you do
this, the compiler creates a variable in a location in memory that prevents it from being overwritten
each time the function is called (you will learn more about C++ memory management in Chapter
26). The effect of this is that the value stored in the variable is preserved and will increase with each
call. The non-
static
variable in Listing 9-1 always contained 0 when it was printed out, whereas the
variable in Listing 9-2 will print 0 on the first call, 1 on the second call, and so on.
The use of
static
local variables is a practice I wouldn't recommend for normal code as it
encourages you to take shortcuts in the design of your code. These shortcuts almost always cause
you more difficult problems in the longer term. You'll see how private member variables can be used
instead when we cover classes. It can be useful to use
static
variables to count the number of
times a function has been called or to time how long the execution of those function calls takes, but
static
local variables are rarely the best design choice for standard game code.
Using static class Member Variables
The
static
keyword can also be used with
class
member variables. Listing 9-3 shows an example
class
that contains a
static
member variable.