Chapter 28 of 37

Storage Classes

When we create a variable in C, there are a few important things to consider, such as where the variable is stored, how long it exists, and where it can be accessed.

Storage classes help define these properties.

What is a Storage Class?

A storage class specifies the scope, lifetime, and linkage of a variable or function.

The main storage-class specifiers in C are:

Storage Class

Main Use

auto

Default for local variables

register

Suggests storing a variable in a CPU register

static

Preserves a variable's value between function calls or gives internal linkage at file scope

extern

Refers to a variable or function defined elsewhere


1. auto

auto is the default storage class for local variables.

void display()
{
    auto int age = 20;
}

Usually, we simply write:

int age = 20;

because local variables are automatically auto.

The variable exists while its block is executing.


2. register

The register keyword suggests that a variable may be stored in a CPU register for faster access.

register int count;

It is only a request to the compiler; the compiler can choose whether or not to honor it.

You also cannot use the address-of operator (&) on a variable declared with register.


3. static

static has different effects depending on where it is used.

Static Local Variable

A static local variable retains its value between function calls.

void count()
{
    static int x = 0;

    x++;
    printf("%d\n", x);
}

If we call count() three times:

1
2
3

Unlike a normal local variable, x is not recreated with its initial value on every call.

Static at File Scope

A file-scope static variable or function has internal linkage, meaning it is accessible only within that source file.

This is useful for hiding implementation details inside a .c file.


4. extern

extern is used to declare a variable or function that is defined elsewhere, often in another source file.

For example:

extern int count;

This tells the compiler that count exists somewhere else; it does not normally create a new definition of the variable.

It is commonly used when working with multiple C source files.


Storage Classes at a Glance

Storage Class

Lifetime

Typical Scope/Linkage

auto

Until the block ends

Local

register

Until the block ends

Local

static local

Entire program

Local scope

static file-scope

Entire program

Internal linkage

extern

Depends on the definition

Refers to external linkage

In Simple Words

Storage classes tell C how a variable or function should behave in terms of lifetime, visibility, and linkage.

The most important ones to remember are:

auto → Default local variable

register → Request register storage

static → Preserves value / limits file visibility depending on context

extern → Refers to a definition elsewhere