Storage Classes

Home / C Programming / Storage Classes

Storage Classes


In C programming, storage classes are keywords used to define the scope, lifetime, and initial value of variables. C provides four storage classes:

Automatic (auto) Storage Class:

Variables declared within a function block (local variables) without any storage class specifier are considered to have the auto storage class by default.

These variables have automatic storage duration, meaning they are created when the block is entered and destroyed when the block is exited.

The initial value of an auto variable is undefined unless explicitly initialized.

Example:


Static Storage Class:

Variables declared with the static storage class specifier have static storage duration, meaning they are created at the start of the program and persist throughout the program's execution.

static variables retain their values between function calls, unlike auto variables that are re-initialized each time the function is called.

If not explicitly initialized, static variables are automatically initialized to zero (or equivalent for non-integer types).

Example:


Register Storage Class:

The register storage class specifier is used to suggest that a variable should be stored in a CPU register for faster access.

The compiler may or may not use a register for the variable, depending on various factors.

The register storage class is rarely used in modern C programming since modern compilers are optimized and can automatically decide which variables to store in registers.

Example:


External (Extern) Storage Class:

The extern storage class specifier is used to declare a variable that is defined in another file or translation unit.

It is used when you want to share the same variable among multiple files.

The extern keyword is typically used in the header files to declare global variables that are defined in source files.

Example:


These are the four storage classes available in C programming, each serving different purposes and useful in various situations. Understanding storage classes is crucial for managing the scope and lifetime of variables efficiently in your C programs.