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
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
-
From Beej’s Guide to C Programming. ↩