Skip to content

C variable storage classes: auto, static, register, extern

In C, variables can have a number of different storage classes (not to be confused with qualifiers like const), as the title of the article lists, they are:

  • auto
  • static
  • register
  • extern

These types dictates where the variables are located, their life time and how they are accessed. Each variable can only be assigned one storage class, so the code below is invalid:

extern static int i;

We will talk about them in turn below

These are the most common. All the variables defined in a code block are auto by default.

Auto variables are initialized to undefined values until a valid assignment (of that type). The keyword indicates that the variable can only be used within the current block since the variable will be automatically created and destroyed as it is needed. This also means that auto variables cannot be global.

void a(void) {
    int i;
    // equivalent to auto int i;

register class variables are only stored in registers instead of in memory. This also means that the variable can only be as big as a register, and do not have an address (no & operator). Note that this is only a hint to modern compilers that the variable will be used extensively. Compilers often will perform this optimization (and better than humans too).

Also note that the register keyword can only be used for local variables, this is because global or static variables, because global variables have static storage by default.

Static variables are initialized first during compilation, this means that the initialization must be a constant. They also persist after their scope )the current block of code) is done, and retain their value through calls.

Extern storage class defines a global variable visible to all object files when linking. Extern variables cannot be initialized since it is only pointing to the storage location of the actual variable. The file that contains the actual variable may initialize.

For example:

int i = 6;


extern int i;

Both files must be compiled together (actually if you only compile file1 is ok, but file2 require a link to file1)

There are a number of nuances, such as static implies internal linkage but extern implies external linkage, so global variables defined as

int i;

is not exactly the same as

static int i;

The first one has static storage (duration of variable) and external linkage (visibility of variable), where as the second has static storage and internal linkage (since static keyword controls both duration=static and visibility=internal).

We will touch on this in another article on linkage

Posted in C/C++. Tagged with , , , , , , , .