Storage-class specifiers give compilers more information about the type of a variable. They are created before the main() function is called.

A common one is the static specifier, where a single instance of the variable will exist, shared between calls. In other words, it’s a global variable — regardless of how many times it’s called or how many objects it may be in. Contrast this with the ordinary local variables we’ve been using before — they’re automatically created and destroyed as the function is called.

This is hard to understand on its own, so here’s an example:1

void counter (void) {
	static int count = 1; // This is initialized one time
	printf("This has been called %d time(s)\n", count);
	count++;
}
 
int main (void) {
	counter(); // "This has been called 1 time(s)"
	counter(); // "This has been called 2 time(s)"
	counter(); // "This has been called 3 time(s)"
	counter(); // "This has been called 4 time(s)"
}

By default static variables are initialised to 0. A useful application of this is in class definitions, where we can create a public static int that counts how many objects have been declared, where the constructor increments it and the destructor decrements it.

static functions are local only to the file it’s defined/declared in. For that purpose, we should avoid putting definitions in header files.

See also

Footnotes

  1. From Beej’s Guide to C Programming.