Storage Classes
Storage Classes
What are Storage Classes?
Storage classes in C define a variable's scope, lifetime, default value and storage location.
| Storage Class | Scope | Lifetime | Default Value |
|---|---|---|---|
| auto | Block | Till block ends | Garbage |
| register | Block | Till block ends | Garbage |
| static | Block/File | Whole program | 0 |
| extern | Global | Whole program | 0 |
auto Storage Class
auto is the default storage class for local variables.
#include <stdio.h>
int main() {
auto int x = 10; // same as int x = 10;
printf("x = %d", x);
return 0;
}register Storage Class
register requests the compiler to store a variable in CPU register for faster access. Modern compilers decide optimization themselves, so this keyword is rarely needed.
#include <stdio.h>
int main() {
register int i;
for(i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}You cannot take the address of a register variable using &.
static Storage Class
A static local variable keeps its value between function calls.
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("Count = %d\n", count);
}
int main() {
counter();
counter();
counter();
return 0;
}extern Storage Class
extern tells the compiler that a global variable is declared somewhere else, possibly in another file.
// file1.c
int total = 100;
// file2.c
#include <stdio.h>
extern int total;
int main() {
printf("Total = %d", total);
return 0;
}Summary
autois default for local variablesregisteris for fast access requeststaticpreserves value for whole program lifetimeexternrefers to a global variable defined elsewhere- Storage class controls scope and lifetime
Storage Classes क्या हैं?
C में storage classes variable की scope, lifetime, default value और storage location define करती हैं।
| Storage Class | Scope | Lifetime | Default |
|---|---|---|---|
| auto | Block | Block खत्म होने तक | Garbage |
| register | Block | Block खत्म होने तक | Garbage |
| static | Block/File | Whole program | 0 |
| extern | Global | Whole program | 0 |
auto
Local variables के लिए auto default storage class है।
auto int x = 10; // same as int x = 10;
register
register compiler से request करता है कि variable को CPU register में रखे। Modern compilers खुद optimization करते हैं।
register int i;
for(i = 1; i <= 5; i++)
printf("%d ", i);static
Static local variable function calls के बीच अपनी value preserve रखता है।
void counter() {
static int count = 0;
count++;
printf("%d\n", count);
}extern
extern बताता है कि variable की definition किसी दूसरी file या जगह पर है।
extern int total;
printf("%d", total);सारांश
- auto local variable का default है
- register fast access की request करता है
- static value को preserve रखता है
- extern दूसरी जगह defined global variable को access करता है
- Storage class scope और lifetime control करती है