C Storage Classes
Every variable has a lifetime (how long it exists) and a linkage (which files can see it). The keywords static and extern change them. Together these are called storage classes.
Automatic local variables
An ordinary local variable is created each time its block starts and destroyed when it ends. That is called automatic storage. Its value does not survive between calls.
static local variables
A local variable marked static is created once, keeps its value between calls, and lives until the program ends. It is still only visible inside its function.
#include <stdio.h>
int nextTicket(void) {
static int counter = 0; // set to 0 only once
counter++;
return counter;
}
int main(void) {
printf("Ticket %d\n", nextTicket());
printf("Ticket %d\n", nextTicket());
printf("Ticket %d\n", nextTicket());
return 0;
}Ticket 1 Ticket 2 Ticket 3
Without static, every call would print Ticket 1. A static local is also set to zero automatically if you give it no value, unlike an automatic local.
static global variables and functions
At file level, static means "private to this file": a static global variable or function cannot be used from other .c files. Use it for helpers and data that are details of one file, so they cannot clash with names in other files.
static int messageCount = 0; // only this file sees it
static void logMessage(const char *msg) { // only this file can call it
messageCount++;
printf("[%d] %s\n", messageCount, msg);
}extern: sharing a variable across files
A global variable is defined in exactly one .c file. Other files that need it declare it with extern, usually in a header:
/* settings.h */
extern int volume; // declaration: "volume exists somewhere"
/* settings.c */
int volume = 5; // definition: the variable itselfAny file that includes settings.h can now read and change volume. Shared global variables make programs harder to follow, so use them sparingly.
const and register
const (see Constants) is not a storage class but often appears with them: static const double RATE = 0.07; is a private constant. register, an old hint to keep a variable in a processor register, is ignored by modern compilers and should not be used.
Practice exercises
- Write a function that prints how many times it has been called, using a
staticlocal. - Make a function that returns the next number of a sequence 1, 1, 2, 3, 5, … on each call, keeping the last two numbers in
staticvariables. - In a two-file project, share an
intwithexternand change it from both files.