A variable declaration can also be preceded by a storage-class specifier:
auto, extern, register or static. Here we will
only describe static, and refer the reader to a more complete
reference manual for descriptions of the others.
Variables declared at the start of a compound-statement are only visible inside
that compound-statement. Normally, each time the thread of execution enters a
compound-statement, space is allocated for these variables and, if necessary, they
are initialized. When it leaves, the space occupied by the variables
is reclaimed and the value held by the variable is lost. If the
declaration is prefixed with static, the variable will not be
destroyed when compound-statement is left, and its value will be preserved. For
example:
|
float f(float x) {
static int init = 0;
if (init == 0) {
/* put setup code here */
init = 1;
}
/* by now things will be setup */
}
|
f which must do some complex setup when
its called for the first time. By using a static variable, we can
tell when this happens. init will be initialized to zero as the
program is loaded, and the first time f is called the setup code
will run, and set init to one. On subsequent calls to f,
init will still be one and the setup code will not be repeated.