Static Variables in C

The definition of static as an adjective is: Lacking in movement, action, or change, esp. in a way viewed as undesirable or uninteresting: “the whole ballet appeared too static”. Well guess what, that is essentially what it means for your C variables declared as static as well. Static variables come in quite handy if you need to record a value between function calls, rather than having an ephemeral variable that loses its previous value for each iteration.

A static variables lifetime exists during the entire execution of the program, rather than local variables that only exist within the scope of the function. To illustrate the use of a static variable here is an example for your perusal:

#include <stdio.h>
 
void static_function_test() {
        static int a = 0; // x is initialized only once, on initial call
        fprintf(stdout, "%d\n", a);
        a++;
}
 
int main(int argc, char **argv) {
       static_function_test(); // prints 0
       static_function_test(); // prints 1
       static_function_test(); // prints 2
       return 0;
}

If I did not declare ‘int a’ as static, then every time I called the ‘static_function_test()’ function, the output of ‘a’ would always be 0. Using the static declaration is useful for counters or any instance where you need to have a variable always retain its previous value.

In C, the static declaration is actually known as a storage classFrom Wikipedia:

1. Static global variables: variables declared as static at the top level of a source file (outside any function definitions) are only visible throughout that file (“file scope”, also known as “internal linkage”).

2. Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

There is only one thing left to do, go try it out yourself!