The static storage class specifier
Objects declared with the static
storage
class specifier have static storage duration, which means that
memory for these objects is allocated when the program begins running
and is freed when the program terminates. Static storage duration
for a variable is different from file or global scope: a variable
can have static duration but local scope.
The keyword static
is the major
mechanism in C to enforce information hiding.
C++ enforces information hiding through the namespace
language feature and the access control of classes. The use of the
keyword static
to limit the scope of external variables
is deprecated for declaring objects in namespace scope.
static
storage class specifier can
be applied to the following declarations: - Data objects
- Class members
- Anonymous unions
static
storage class
specifier with the following: - Type declarations
- Function parameters
At the C99 language level, the static
keyword
can be used in the declaration of an array parameter to a function.
The static
keyword indicates that the argument passed
into the function is a pointer to an array of at least the specified
size. In this way, the compiler is informed that the pointer argument
is never null. See Static array indices in function parameter declarations (C only) for more
information.
Linkage of static variables
static
storage class specifier
and has file scope, the identifier has internal
linkage. Each instance of the particular identifier therefore represents
the same object within one file only. If a declaration
of an object contains the static storage class specifier and has function
scope, an object is statically allocated and all the function calls
use the same object. For example, if a static variable x
has
been declared in function f
, when the program exits
the scope of f
, x
is not destroyed:#include <stdio.h>
int f(void) {
static int x = 0;
x++;
return x;
}
int main(void) {
int j;
for (j = 0; j < 5; j++) {
printf("Value of f(): %d\n", f());
}
return 0;
}
The following is the output of the above example: Value of f(): 1
Value of f(): 2
Value of f(): 3
Value of f(): 4
Value of f(): 5
Because x
is a function
local static variable, it is not reinitialized to 0
on
successive calls to f
.