In C Language, storage classes determine the scope, visibility, and lifetime of variables.
There are four main storage classes in C Language: `auto`, `register`, `static`, and `extern`.
Scope Control: It control the scope of variables, determining where they can be accessed within a program.
Lifetime Management: It dictate the lifetime of variables, determining when they are created, initialized, and destroyed.
Memory Efficiency: Proper use of storage classes can optimize memory usage and improve program performance.
This is the default storage class for all local variables.
Variables declared as "auto" are automatically created when the block they are defined in is entered and destroyed when the block is exited.
However, "auto" is rarely explicitly used since it's the default behaviour for local variables.
#include <stdio.h> int main() { auto int x = 10; // 'auto' is rarely used explicitly printf("Value of x: %d\n", x); return 0; }
#include <stdio.h> int main() { register int x = 10; // Requesting to store 'x' in a register printf("Value of x: %d\n", x); return 0; }
The "register" storage class is used to define local variables that should be stored in a register instead of RAM.
However, modern compilers are smart enough to decide when to use registers for variables, so the "register" keyword is rarely used nowadays and might be ignored by compilers.
#include <stdio.h> void increment() { static int count = 0; // 'count' retains its value between function calls count++; printf("Count: %d\n", count); } int main() { increment(); // Count: 1 increment(); // Count: 2 increment(); // Count: 3 return 0; }
// File: file1.c #include <stdio.h> int global_var = 10; // Definition of global variable void display() { printf("Global variable: %d\n", global_var); } // File: file2.c #include <stdio.h> extern int global_var; // Declaration of global variable int main() { global_var = 20; // Modifying the value of global variable display(); // Global variable: 20 return 0; }
The "static" storage class is used to declare local variables that retain their value between function calls.
When a variable is declared as static, it is allocated memory in the data segment of the program instead of the stack, and its value persists throughout the program's execution.
The "extern" storage class is used to declare variables that are defined in other source files.
It's commonly used to declare global variables or functions that are defined in another file.
When we use "extern", we're telling the compiler that the variable or function is defined elsewhere, and the actual definition will be resolved at linking time.
Additionally, C also has a storage class specifier called "typedef", which is used to create new data type names for existing data types.
It does not actually allocate storage, but it's important for creating aliases for data types, improving code readability, and enhancing portability.