When a variable with block scope is declared to be static
,
it is implemented in the same section of memory as variables that have file scope
(those variables declared outside of any function).
This section of memory is sometimes called "static memory".
Otherwise, variables with block scope are implemented on the run-time stack.
Variables implemented in static memory are persistent. They remain in existence for as long as the program is running. A value assigned to a variable in static memory will be available anywhere the variable is in scope. The value will not change unless another value is assigned to it.
A variable implemented on the run-time stack is created (pushed onto the stack) when control enters the variable's block. It is destroyed (popped off the stack) when control leaves the block. Such variables are called automatic because they are automatically created on entry to a block and automatically destroyed on exit from a block. Values assigned to an automatic variable are available only when control is inside the variable's block.
If a static
variable that is declared inside a block is initialized,
that initialization is done only once, the first time control enters the block.
If a value is assigned to the variable later in the block, that value will be retained
even after control leaves the block. The initialization
will not be performed the next time control enters the block.
If an automatic variable that is declared inside a block is initialized, that initialization is done every time control enters the block when the variable is created. If a value is assigned to the variable later in the block, that value will be lost when control leaves the block.
static
variables are initialized to zero, by default.
Automatic variables are not initialized by default.
They should be initialized in the declaration or with explicit assignment statements.
Here is a table that summarizes some of these rules:
Location of Variable Declaration | Scope | Linkage | Storage | ||
---|---|---|---|---|---|
variable not declared as static | variable is declared as static | variable not declared as static | variable is declared as static | ||
outside of any block (global variable) |
File Scope | External | Internal Linkage | Static | Static |
inside a block (local variable) |
Block Scope | No Linkage | No Linkage | Automatic (on the stack) | Static |
in a parameter list | Block Scope | No Linkage | --- | Automatic (on the stack) | --- |