The life time of parameter and local variables

  • Parameter variables and local variables of a function are created (= allocated) when the function is invoked (= called)

  • Initialization of local variables:

      • Each time a local variable is created, the local variable will be initialized !


  • Parameter variables and local variables of a function are destroyed (= de-allocated) when the function returns (= ends)

The life time of global,   static global  and   static local variables

  • Global variables, static global variables and static local variables are created (= allocated) when the program starts running

  • Initialization:

      • Global variables, static global variables and static local variables are initialized at the start of the program.


  • Global variables, static global variables and static local variables are destroyed (= de-allocated) when the C program exits (= ends)

Quiz:   what is printed by this C program ?

Apply whet you just learned and figure out what this program will print out:

   #include <stdio.h>

   void f( )
   {
      int        i = 100;       // local variable
      static int j = 100;       // Static local variable

      i++;
      j++;

      printf( "i = %d, j = %d\n", i, j );
   }

   int main( int argc, char* argv[] )                  
   {
      f();   // Calls f() 4 times...
      f();  
      f();   // What is printed by each call ?
      f();
   } 

DEMO: demo/C/set1/kinds-vars2.c

Quiz:   what is printed by this C program ?

Answer:

   #include <stdio.h>

   void f( )
   {
      int        i = 100;       // local variable
      static int j = 100;       // Static local variable

      i++;
      j++;

      printf( "i = %d, j = %d\n", i, j );
   }

   int main( int argc, char* argv[] )                  
   {
      f();   // 101  101
      f();   // 101  102
      f();   // 101  103
      f();   // 101  104
   } 

Because i is initialized to 100 ==> each time the function f( ) is called, it executes i = 100 + 1 = 101
Because j is initialized at the start (only) ==> each time the function f( ) is called, j is incremented