Lesson 09·C Programming

Storage Classes

Determining scope, lifetime, memory placement, and initial value of variables

What is a Storage Class?

'Storage' refers to the scope of a variable and the physical memory allocated by the compiler. A storage class defines two essential properties: the lifetime of the variable and its scope of visibility.

Variables can reside in two physical locations: Main Memory (RAM) or high-speed CPU Registers.

1. Automatic Storage Class (auto)

Keyword
auto
Storage Location
Main Memory (Stack)
Initial Value
Garbage (unpredictable)
Scope
Local to the declaring block
Life
Till control remains within the block
C Example
#include <stdio.h>

void main() {
    auto int i = 10;
    {
        auto int i = 20;
        printf("Inner block i: %d\n", i);
    }
    printf("Outer block i: %d\n", i);
}
Program Output
Inner block i: 20
Outer block i: 10

2. Register Storage Class (register)

Variables stored in CPU registers can be accessed substantially faster than those in RAM:

Keyword
register
Storage Location
CPU Registers
Initial Value
Garbage
Scope
Local to the declaring block
Life
Till control remains within the block
C Example
#include <stdio.h>

void main() {
    register int counter;
    for (counter = 1; counter <= 3; counter++) {
        printf("Counter: %d\n", counter);
    }
}
Program Output
Counter: 1
Counter: 2
Counter: 3

3. Static Storage Class (static)

Static variables preserve their values between multiple function invocations:

Keyword
static
Storage Location
Main Memory (Data Segment)
Initial Value
Zero (0) automatically
Scope
Local to the block where declared
Life
Persists throughout the entire program
C Example
#include <stdio.h>

void incre(void) {
    int avar = 1;         // Automatic variable: re-initialized every call
    static int svar = 1;  // Static variable: initialized once only

    avar++;
    svar++;

    printf("Automatic variable: %d | Static variable: %d\n", avar, svar);
}

void main() {
    int i;
    for (i = 0; i < 3; i++) {
        incre();
    }
}
Program Output
Automatic variable: 2 | Static variable: 2
Automatic variable: 2 | Static variable: 3
Automatic variable: 2 | Static variable: 4

4. External Storage Class (extern)

External variables are declared outside functions and can be referenced globally:

Keyword
extern
Storage Location
Main Memory
Initial Value
Zero (0)
Scope
Global (accessible across program files)
Life
Until the program terminates
C Example
#include <stdio.h>

int i = 20;  // Global variable definition

void show(void) {
    printf("In show(): %d\n", i);
}

void main() {
    printf("In main(): %d\n", i);
    show();
}
Program Output
In main(): 20
In show(): 20