Static local variables
What you'll learn: How to make a variable inside a function remember its value even after the function finishes running.
The persistent helper
Normally, when a function ends, it suffers from total amnesia. Any variable you declared inside it is wiped from memory, and the next time you call that function, it starts over from scratch. These are called "automatic" variables.
But sometimes, you need a function to have a memory. Imagine a ticket counter at a theater. Each time a customer arrives (a function call), the clerk needs to know what the last ticket number issued was so they can provide the next one. If the clerk forgot everything the moment a customer walked away, they would just give every single person "Ticket #1."
In C, we use the static keyword to give a local variable this "long-term memory."
How it works
When you put static in front of a variable declaration inside a function, two special things happen:
- The variable is initialized only once, the very first time the function is called.
- The variable stays in memory until the entire program ends.
Even though the variable stays alive, it is still "local." This means only the function it lives in can see or change it. It’s like a private diary that stays on the function's desk; no one else can read it, but the information inside survives overnight.
Seeing it in action
Compare how a normal variable behaves versus a static one in this example:
#include <stdio.h>
void pressButton() {
int normalCount = 0; // Reset to 0 every time
static int staticCount = 0; // Initialized ONLY once
normalCount++;
staticCount++;
printf("Normal: %d, Static: %d\n", normalCount, staticCount);
}
int main() {
pressButton(); // Output: Normal: 1, Static: 1
pressButton(); // Output: Normal: 1, Static: 2
pressButton(); // Output: Normal: 1, Static: 3
return 0;
}
In the code above, normalCount is born and dies with every function call. But staticCount survives. It remembers that it was incremented to 1, so the next time the button is "pressed," it picks up where it left off and becomes 2.
Key takeaway
A static local variable is a private variable that keeps its value between multiple function calls.