C - Function Static Variables

Introduction

You could declare a static variable count with this declaration:

static int count = 0;

static is a keyword.

A static variable doesn't get destroyed when execution leaves the function.

A static variable is initialized only once, right at the beginning of the program.

A static variable is visible only within the function that contains its declaration, it is essentially a global variable.

All static variables are initialized to 0 by default if you don't specify an initial value.

The following code shows the difference between static variables and automatic variables.

Demo

#include <stdio.h>

// Function prototypes
void test1(void);
void test2(void);

int main(void)
{
  for (int i = 0; i < 5; ++i)
  {/*  w  w  w .  j  av  a 2s.  co m*/
    test1();
    test2();
  }
  return 0;
}
// Function test1 with an automatic variable
void test1(void)
{
  int count = 0;
  printf("test1   count = %d\n", ++count);
}

// Function test2 with a static variable
void test2(void)
{
  static int count = 0;
  printf("test2   count = %d\n", ++count);
}

Result

The two variables called count are defined in the code above.

The static variable count is declared in the function test2():

Related Topics