Loading, please wait...

Static Storage Class

Keywords extern and static are used in the declarations of identifiers for variables and functions of static storage duration. Identifiers of static storage duration exist from the time at which the program begins execution. For static variables, storage is allocated and initialized once, when the program begins execution.

For functions, the name of the function exists when the program begins execution. However, even though the variables and the function names exist from the start of program execution, this does not mean that these identifiers can be accessed throughout the program.

There are two types of identifiers with static storage duration: external identifiers (such as global variables and function names) and local variables declared with the storage class specifier static. Global variables and function names are of storage class extern by default. Global variables are created by placing variable declarations outside any function definition, and they retain their values throughout the execution of the program. Global variables and functions can be referenced by any function that follows their declarations or definitions in the file. This is one reason for using function prototypes—when we include stdio.h in a program that calls printf, the function prototype is placed at the start of our file to make the name printf known to the rest of the file.

Defining a variable as global rather than local allows unintended side effects to occur when a function that does not need access to the variable accidentally or maliciously modifies it. In general, use of global variables should be avoided except in certain situations with unique performance requirements.

Variables used only in a particular function should be defined as local variables in that function rather than as external variables.

Local variables declared with the keyword static are still known only in the function in which they’re defined, but unlike automatic variables, static local variables retain their value when the function is exited. The next time the function is called, the static local variable contains the value it had when the function last exited. The following statement declares local variable count to be static and to be initialized to 1.

static int count = 1;

All numeric variables of static storage duration are initialized to zero if you do not explicitly initialize them.

Keywords extern and static have special meaning when explicitly applied to external identifiers.