Introduction
In the variable declaration you can also define lifetime or storage duration of the variable. Lifetime indicates the length of time the variable value is guaranteed during execution. For example, if the variable is defined inside the function, its value is kept until the function executes. After completion of the function, the storage allocated for the variable is freed.
Program
#include
int g = 10; \\ A
main()
{
int i =0; \\ B
void f1(); \\ C
f1(); \\ D
printf(" after first call \n");
f1(); \\ E
printf("after second call \n");
f1(); \\ F
printf("after third call \n");
}
void f1()
{
static int k=0; \\ G
int j = 10; \\ H
printf("value of k %d j %d",k,j);
k=k+10;
}
Explanation
Variables in C language can have automatic or static lifetimes. Automatic means the variable is in existence until the function in which it is defined executes; static means the variable is retained until the program executes.
The variable that is defined outside the function, such as g in statement A, is called a global variable because it is accessible from all the functions. These global variables have static lifetimes, that is, variable return throughout the program execution. The value of the variable, as updated from one function, affects another function that refers to that variable. It means that the updating in this variable is visible to all functions.
Variables such as i, defined in main, or j, defined in f1, are of the automatic type; i exists until main is completed and j exists until f1 is completed.
You can define the lifetime of a local variable in a function as given in statement G. The variable k has a static lifetime; its value is returned throughout the execution of the program.
The function f1 increments the value of k by 10 and prints the values of j and k.
When you call the function for the first time using statement D, k is printed as 0, j is printed as 10, k is incremented to 10, the space of j is reallocated, and j ceases to exist.
When you call the function the second time, it will give 10 (the previous value of k) because k is a static variable. There are reallocations for j so j is printed as 10.
When you call the function the third time, j is still printed as 10.
Points to Remember
The variables in C can have static or automatic lifetimes.
When a variable has a static lifetime, memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates.
When a variable has an automatic lifetime, the memory is allocated to the variable when the function is called and it is deallocated once the function completes its execution.
Global variables have static lifetimes.
By default, local variables have automatic lifetimes.
To make a local variable static, use the storage-class specifier.
No comments:
Post a Comment