Special storage variables
 

  • The C language provides a static modifier that alters some property of local and global variables

  • A local variable or a global variable can be modified by using the static keyword

  • The modified variables are called:

      • Static local variables        and         
      • Static global variables

static local variables
 

  • The life time of a local variable is modified by the static keyword

  • The life time of a static local variable is the entire duration of the running program

    I.e.: a static local variable is not destroyed when a function returns (= exits) !!

  • Important consequence:

      • A static local variable will only be initialized once

    because initialization is done when the variable is created.

The usage of static local variables

Keep a count on the # times that a function was invoked:

   #include <stdio.h>

   void f( )
   {
      int i = 0;         // Normal local
      static int j = 0;  // Static local 

      i++;
      j++;

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

   int main( int argc, char* argv[] )                  
   {
      f();
      f();
      f();
   } 

The static local variable j will keep the count !

static global variables
 

  • The scope of a global variable is modified by the static keyword

  • The scope of a static global variable is limited to the program file that contains the static global variable

    (Ordinary global variables has score in all program files !)

  • Comment:

      • The static glabal variable was introduced later into the C language due to influence of the private classifier in C++/Java that limits the access location to the variable

The usage of static global variables
 

Consider: a previous example on global variables in 2 program files:

progFile1.c progFile2.c
 #include <stdio.h>

 extern int x, y;  

 int main( int argc, char* argv[] ) 
 {
    f( );
    printf( "%d  %d\n", x, y );
 } 
   
 int x;     
 int y = 4;                    

 int f( )
 {
    x = y + 3;
 }



   

The main( ) function can access the global variables

The usage of static global variables
 

When we change the variable y into a static global:

progFile1.c progFile2.c
 #include <stdio.h>

 extern int x, y;  

 int main( int argc, char* argv[] ) 
 {
    f( );
    printf( "%d  %d\n", x, y );
 } 
   
 static int x;     
 int y = 4;                  

 int f( )
 {
    x = y + 3;
 }

 // Bugs related to x must be
 // in functions in this file !
   

The main( ) function cannot access the variable x !!! (compile error)
DEMO: /home/cs255001/demo/tmp/demo.c + demo2.c

Usage:   static global can limit to search for erroneous to the program file that contains the static global variable