Examples Using static Storage Classes

The following program shows the linkage of static identifiers at file scope. This program uses two different external static identifiers named stat_var. The first definition occurs in File 1. The second definition occurs in File 2. The main function references the object defined in File 1.. The var_print function references the object defined in File 2.

File 1

/**************************************************************
** Program to illustrate file scope static variables         **
**************************************************************/
 
#include <stdio.h>
 
extern void var_print(void);
static stat_var = 1;
 
int main(void)
{
   printf("file1 stat_var = %d\n", stat_var);
   var_print();
   printf("FILE1 stat_var = %d\n", stat_var);
 
   return(0);
}

 

File 2

/**************************************************************
** This file contains the second definition of stat_var      **
**************************************************************/
 
#include <stdio.h>
 
static int stat_var = 2;
 
void var_print(void)
{
    printf("file2 stat_var = %d\n", stat_var);
}

This program produces the following output:

file1 stat_var = 1
file2 stat_var = 2
FILE1 stat_var = 1

The following program shows the linkage of static identifiers with block scope. The test function defines the static variable stat_var, which retains its storage throughout the program, even though test is the only function that can refer to stat_var.

/**************************************************************
** Program to illustrate block scope static variables        **
**************************************************************/
 
#include <stdio.h>
 
int main(void)
{
   void test(void);
   int counter;
   for (counter = 1; counter <= 4; ++counter)
      test();
 
   return(0);
}
 
void test(void)
{
   static int stat_var = 0;
   auto int auto_var = 0;
   stat_var++;
   auto_var++;
   printf("stat_var = %d auto_var = %d\n", stat_var, auto_var);
}

This program produces the following output:

stat_var = 1 auto_var = 1
stat_var = 2 auto_var = 1
stat_var = 3 auto_var = 1
stat_var = 4 auto_var = 1


static Storage Class