Linkage of static variables

A declaration of an object that contains the static storage class specifier and has file scope gives the identifier internal linkage. Each instance of the particular identifier therefore represents the same object within one file only. For example, if a static variable x has been declared in function f, when the program exits the scope of f, x is not destroyed:

#include <stdio.h>

int f(void) {
  static int x = 0;
  x++;
  return x;
}

int main(void) {
  int j;
  for (j = 0; j < 5; j++) {
    printf("Value of f(): %d\n", f());
  }
  return 0;
}

The following is the output of the above example:

Value of f(): 1
Value of f(): 2
Value of f(): 3
Value of f(): 4
Value of f(): 5

Because x is a static variable, it is not reinitialized to 0 on successive calls to f.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]