|
|
|
|
|
|
|
the variables are alive while the function is executing, and finally the storage is destroyed (deallocated) when the function exits. In contrast, the lifetime of a global variable is the lifetime of the entire program. Memory is allocated only once, when the program begins executing, and is deallocated only when the entire program terminates. Observe that scope is a compiletime issue, but lifetime is a run-time issue. |
|
|
|
 |
|
 |
|
|
Lifetime The period of time during program execution when an identifier has memory allocated to it. |
|
|
|
|
|
|
|
|
In C++, each variable has a storage class that determines its lifetime. An automatic variable is one whose storage is allocated at block entry and deallocated at block exit. A static variable is one whose storage remains allocated for the duration of the entire program. All global variables are static variables. By default, variables declared within a block are automatic variables. However, you can use the reserved word static when you declare a local variable. If you do so, the variable is a static variable and its lifetime persists from function call to function call: |
|
|
|
|
|
|
|
|
void SomeFunc()
{
float someFloat; // Destroyed when function exits
static int someInt; // Retains its value from call to call
.
.
.
} |
|
|
|
|
|
|
|
|
It is usually better to declare a local variable as static than to use a global variable. Like a global variable, its memory remains allocated throughout the lifetime of the entire program. But unlike a global variable, its local scope prevents other functions in the program from tinkering with it. |
|
|
|
 |
|
 |
|
|
Automatic Variable A variable for which memory is allocated and deallocated when control enters and exits the block in which it is declared. |
|
|
|
 |
|
 |
|
|
Static Variable A variable for which memory remains allocated throughout the execution of the entire program. |
|
|
|
|
|