Programming: Static Variables

A static variable is a variable that is only initialized once and is not destroyed when a function terminates. Typically, when you call a function, any variables declared within that function will be discarded when the function returns. This means whatever value they may have had in a previous function call has no bearing on future function calls. A static variable, by contrast, will not disappear after the function call has been terminated. Let us take the following code, for example: 

int main(void) {

    int n = 0;

    while (n < 5) {

        increaseCounter();

        n++;

    }

}


void increaseCounter() {

    int localCounter = 0;

    localCounter++;

}

If we looked at the debugger while this code executed, we would see the following behavior: when increaseCounter() is called for the fifth time, localCounter will be at 1 at the end of the increaseCounter() function. In essence, the localCounter does not increase five times as the main loop seems to suggest; instead, the localCounter is reset and then incremented with every iteration. If we add the static keyword to the localCounter variable, the story becomes different.

void increaseCounter() {

    static int localCounter = 0;

    localCounter++;

}

Now, if we look through the debugger, we will notice that, on the first iteration, localCounter is initialized to 0, then incremented. On the second iteration, the variable declaration is skipped entirely. Why? Because localCounter was already declared during the first iteration. Now, at the end of the second iteration, localCounter will have a value of 2. At the end of the third iteration, it will have a value of 3, and so on and so forth, where it will reach a final value of 5 upon the fifth iteration.

The static variables are still local to the function they are defined within. In other words, other functions cannot access them. However, they are not maintained on the stack like other "automatic" variables and they are stored on the data segment of the memory.