By Stephen R. Davis

A variable in C++ should be assigned a storage type depending upon where and how it is defined. Variables defined within a function like nLocalVariable don’t exist until control passes through the declaration. In addition, nLocalVariable is only defined within fn() — the variable ceases to exist when control exits the fn() function.

int nGlobalVariable;
void fn()
    int nLocalVariable;
    static int nStaticVariable = 1;
    nStaticVariable = 2;

By comparison, the variable nGlobalVariable is created when the program begins execution and exists as long as the program is running. All functions have access to nGlobalVariable all the time.

nLocalVariable has local scope, and nGlobalVariable has global scope. The keyword static can be used to create a sort of mishling — something between a global and a local variable. The static variable nStaticVariable is created when execution reaches the declaration the first time that function fn() is called.

Unlike nLocalVariable, however, nStaticVariable is not destroyed when program execution returns from the function. Instead, it retains its value from one call to the next.

In this example, nStaticVariable is initialized to 1 the first time that fn() is called. The function changes its value to 2. nStaticVariable retains the value 2 on every subsequent call — it is not reinitialized once it has been created. The initialization portion of the declaration is ignored every subsequent time that fn() is called after the first time.

However, the scope of nStaticVariable is still local to the function. Code outside of fn() does not have access to nStaticVariable.

Global variables are useful for holding values that you want all functions to have access to. Static variables are most useful for counters — for example, if you want to know how many times a function is called. However, most variables are of the plain ol’ local variety.