0
0
Cprogramming~5 mins

Why storage classes are needed

Choose your learning style9 modes available
Introduction

Storage classes tell the computer how long a variable should keep its value and where it should be stored. This helps organize memory and control variable access.

When you want a variable to keep its value even after a function ends.
When you want to share a variable between different files in a program.
When you want a variable to be created fresh every time a function runs.
When you want to limit a variable's use only inside one file.
When you want to save memory by controlling variable lifetime.
Syntax
C
storage_class data_type variable_name;

Common storage classes in C are auto, register, static, and extern.

If you don't specify a storage class, auto is the default for local variables.

Examples
This variable keeps its value between function calls.
C
static int count = 0;
This tells the program that total is defined in another file.
C
extern int total;
This suggests the variable should be stored in a CPU register for faster access.
C
register int speed;
This is a normal local variable that is created and destroyed each time the function runs.
C
auto int temp;
Sample Program

This program shows how a static variable keeps its value between function calls. Each time demo() runs, count increases and remembers its value.

C
#include <stdio.h>

void demo() {
    static int count = 0;  // keeps value between calls
    count++;
    printf("Count is %d\n", count);
}

int main() {
    demo();
    demo();
    demo();
    return 0;
}
OutputSuccess
Important Notes

Using static inside a function keeps the variable alive between calls but hides it from other functions.

extern helps share variables across different files in a program.

register is a hint to the compiler and may be ignored by modern compilers.

Summary

Storage classes control where and how long variables live in memory.

They help manage variable visibility and lifetime in a program.

Using storage classes properly makes programs more efficient and organized.