C language में जब आप कोई variable बनाते हैं, तो उसकी behavior को define करने के लिए Storage Classes का use किया जाता है। इससे हम जान सकते हैं कि:
C में 4 मुख्य Storage Classes होती हैं:
Storage Class | Default Value | Scope | Lifetime | Location |
---|---|---|---|---|
auto | Garbage | Local | Function ke end tak | Stack |
register | Garbage | Local | Function ke end tak | CPU Register |
static | 0 | Local / Global | Program ke end tak | Data Segment |
extern | Original variable ki value | Global | Program ke end tak | Same as actual variable |
Default storage class होती है जब आप कोई variable function के अंदर declare करते हैं।
#include <stdio.h>
void demo() {
auto int x = 10;
printf("x = %d\n", x);
}
int main() {
demo();
return 0;
}
Note: Modern C में auto
keyword optional होता है। अगर आप नहीं भी लिखें, तो भी local variable auto ही माना जाता है।
Variable को CPU register में store करने के लिए register storage class का use होता है जिससे access fast होता है।
#include <stdio.h>
void test() {
register int count = 5;
printf("count = %d\n", count);
}
Note: आप register variable का address नहीं ले सकते यानी &count
invalid होगा।
Static variable एक बार initialize होता है और program के अंत तक उसकी value memory में रहती है। Function बार-बार call हो तब भी वो value retain रहती है।
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("count = %d\n", count);
}
int main() {
counter();
counter();
counter();
return 0;
}
Output:
count = 1
count = 2
count = 3
Extern का use तब किया जाता है जब आप किसी variable को एक file में declare करके दूसरी file में use करना चाहते हैं।
// file1.c
int x = 10;
// file2.c
extern int x;
printf("x = %d", x);
Note: Extern variable की memory उस जगह से आती है जहाँ इसे originally declare किया गया है।
Storage classes C programming का एक important topic है जिससे आप variables का behavior control कर सकते हैं। Beginner को इसे समझना जरूरी है क्योंकि यही आपको memory, scope और variable lifetime को manage करने में मदद करता है।