C Storage Classes
In this page:
Auto Storage Class
auto is the default storage class for any local variable you declare without specifying one explicitly -- it allocates temporary memory for the current function call and is destroyed automatically once that call ends.
Example: Auto Storage Class
#include <stdio.h>
int main() {
auto int x = 5;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Register Storage Class
register asks the compiler to store a variable directly in a CPU register instead of regular memory (RAM), aiming for faster access -- though modern compilers usually make this optimization decision on their own regardless of the hint.
Example: Register Storage Class
#include <stdio.h>
int main() {
register int i;
for (i = 0; i < 3; i++) {
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Static Storage Class
static changes a local variable's lifetime so it retains its value between separate calls to the same function, instead of resetting each time -- useful for things like a counter that needs to persist across multiple invocations.
Example: Static Storage Class
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("%d ", count);
}
int main() {
counter();
counter();
counter();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Extern Storage Class
extern declares that a variable is defined in a different source file, letting multiple .c files share and modify the same global variable without each one needing its own separate copy.
Example: Extern Storage Class
#include <stdio.h>
int sharedValue = 42;
extern int sharedValue;
int main() {
printf("%d", sharedValue);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Selecting Storage Classes
Choosing the right storage class is about matching intent to behavior: static for a value that must persist across calls, auto for ordinary short-lived locals, and register only as a rarely-needed performance hint on tight loop counters.
Example: Selecting Storage Classes
#include <stdio.h>
void counter() {
static int persistent = 0;
int temporary = 0;
persistent++;
temporary++;
printf("%d %d ", persistent, temporary);
}
int main() {
counter();
counter();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: