Storage Classes (auto, static, extern, register)
void myFunction() {
auto int x = 5; // 'auto' is the default - almost nobody writes it explicitly
int y = 10; // exactly equivalent to the line above
}
Any variable declared inside a function without another storage class keyword is automatically auto by default — it's created when the function starts and destroyed the moment the function returns, which is why it's also called a local variable.
void counter() {
static int count = 0; // initialized only ONCE, ever
count++;
printf("%d\n", count);
}
int main() {
counter(); // prints 1
counter(); // prints 2
counter(); // prints 3 - static remembers its value between calls!
return 0;
}
A regular local variable resets every time a function is called. A static local variable is initialized only the very first time, and then quietly keeps its value between separate calls to the same function — genuinely useful for counters, caches, and similar patterns.
int totalUsers = 0; // global - visible to every function in this file
void addUser() {
totalUsers++; // no need to pass it in - it's globally visible
}
int main() {
addUser();
addUser();
printf("%d\n", totalUsers); // 2
return 0;
}
Global variables can be convenient, but they're generally used sparingly in well-organized code, because any function can silently change them, making bugs harder to trace back to their source.
In larger, multi-file C projects, extern tells the compiler "this global variable is defined in a different file — just trust that it exists and will be linked in later":
// file2.c
extern int totalUsers; // declared elsewhere, defined in file1.c
It's tempting for beginners to make every variable global to avoid passing parameters around. This quickly makes programs hard to debug, because any function anywhere in the file can silently change a global's value, and tracking down which one caused an unexpected change becomes genuinely difficult as programs grow. Prefer passing values as parameters and returning results explicitly wherever possible.
Write a function using a static variable that tracks and prints how many times it has been called, then call it four times from main.
#include <stdio.h>
void trackCalls() {
static int calls = 0;
calls++;
printf("This function has been called %d time(s)\n", calls);
}
int main() {
trackCalls();
trackCalls();
trackCalls();
trackCalls();
return 0;
}