Tuesday, March 22, 2011

program for Storage of Variables with example


Program

#include <stdio.h>
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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. The function f1 increments the value of k by 10 and prints the values of j and k.
  6. 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.
  7. 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.
  8. When you call the function the third time, j is still printed as 10

No comments:

Post a Comment