HOME HTML EDITOR C JAVA PHP

C Storage Classes:

In C, Storage Classes are used to define the scope (visibility), lifetime, and initial value of variables and functions. By telling the compiler where to store a variable and how long it should exist, you can write more memory-efficient and organized code.

1. The Four Standard Storage Classes

C provides four primary storage classes, each serving a specific purpose in memory management:

Storage Class Storage Location Default Value Lifetime
auto Stack (RAM) Garbage End of block
register CPU Register Garbage End of block
static Data Segment Zero (0) End of program
extern Data Segment Zero (0) End of program

2. auto: The Default Class

The auto storage class is the default for all local variables. It is rarely written explicitly because variables declared inside a function are automatically "auto."

void myFunction() {
    auto int x = 10; // Same as 'int x = 10;'
}

3. static: Preserving Values

A static variable remains in memory until the program ends. If declared inside a function, it "remembers" its value between different function calls.

void counter() {
    static int count = 0;
    count++;
    printf("%d ", count);
}
// Calling counter() 3 times will print: 1 2 3

4. register: High-Speed Access

The register keyword suggests to the compiler that the variable be stored in a CPU register instead of RAM for faster access. This is used for variables used frequently, like loop counters.

for (register int i = 0; i < 1000; i++) {
    // High speed execution
}

5. extern: Global Linkage

The extern storage class is used when a variable is defined in one file but needs to be accessed in another. It tells the compiler, "This variable exists somewhere else."

6. Scope vs. Lifetime

Pro Tip: Use the static keyword for global variables that you don't want other files to access. This is known as "Internal Linkage" and is a great way to keep your code modular and private!