C Storage Classes
A storage class says how long a variable lives and where the program can see it. C has three storage words to meet: static, extern, and register.
A static counter
count is static, so it holds its value between calls. The output shows 1, then 2.
#include <stdio.h>
int count_calls(void) {
static int count = 0;
count++;
return count;
}
int main() {
printf("%d\n", count_calls());
printf("%d\n", count_calls());
return 0;
}A plain local starts fresh
count here is a normal local, so it starts at 0 on every call. The output shows 1 twice.
#include <stdio.h>
int fresh_count(void) {
int count = 0;
count++;
return count;
}
int main() {
printf("%d\n", fresh_count());
printf("%d\n", fresh_count());
return 0;
}register as a hint
total carries the register hint, and the loop adds 1, 2, and 3. The output is 6.
#include <stdio.h>
int main() {
register int total = 0;
for (int i = 1; i <= 3; i++) {
total += i;
}
printf("%d\n", total);
return 0;
}Example
#include <stdio.h>
int visit(void) {
static int visits = 0;
visits++;
return visits;
}
int main() {
printf("Visit %d\n", visit());
printf("Visit %d\n", visit());
printf("Visit %d\n", visit());
return 0;
}Key points
- A storage class describes how long a variable lives.
- A static variable inside a function holds its value from one call to the next.
- A normal local variable starts fresh on every call.
- extern says a variable is declared in another file.
- This course keeps every program in one file, so extern is a word to know, not a tool to build with here.
- register is a hint that a variable will be used a lot.
- The compiler may ignore the register hint.
visits is static, so it holds its value from one call to the next. The output counts the visits: 1, then 2, then 3.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a static variable inside a function do?