Static variables and functions

December 14th, 2009 by Kevin | Posted under C Programming.

A static variable is a global variable with it’s scope limited to the function it is declared in. The keyword “static” is used to declare a static variable or function. What this means is a variable declared as static will be initialized with 0 and it will retain it’s value over repeated calls of the function till the program terminates. This is easy to understand from the example below.

void foo()
{
   static int a;   /* Static variable implicitly initialized to zero */
   int b = 0;      /* Automatic variable explicitly initialized to zero */

   a++;
   b++;
   printf("a = %d, b = %dn", a, b);
}

int main()
{
   int i = 0;
   for(i=0; i<3; i++)
   {
      foo();
   }
}

Output is:

a = 1, b = 1

a = 2, b = 1

a = 3, b = 1

If a global variable is declared as static, it’s scope is limited to that module or file. So it cannot be accessed from another module even by using the “extern” keyword. The compiler is bound to complain if used in such a manner.

The use of the keyword “static” also holds true in case of a function. By default a function is global and can be called from any other module. By declaring a function as static, is can be called only from that particular module.

The benefit of using static global variables and static functions is that they are made private to the module they are declared in. This is very useful in creating libraries as it helps shield the functions which are internal to the library and should not be called by the applications that use it.

foo.c


static int gbl1 = 10;
int gbl2 = 5;

static int foo1()
{
   gbl1++;
   gbl2++
}

int foo2()
{
   gbl1++;
   gbl2++;
   foo1();    /* Static function can be accessed from it's own module */
}

main.c

extern int gbl1;              /* Error: Static variable cannot be accessed as extern */
extern int gbl2;

extern int foo1();           /*Static function cannot be accessed as extern */
extern int foo2();

int main()
{
   foo1();    /*Static function cannot be accessed as extern */
   foo2();
   return 0;
}

 

Related Posts:

Tags: ,

Comments

2 Responses to “Static variables and functions”
  1. Ah, this post reminds me of the horrors that were called computer programming I and II in the first year of engineering. :)

    [Reply]

  2. Kevin says:

    Well, I thought the same about mechanics, physics and chemistry :)

    [Reply]

Do you have any comments on Static variables and functions ?

Spam protection by WP Captcha-Free