The static keyword inside functions
What you'll learn: How to use the static keyword to make a variable remember its value between function calls.
The problem with "Automatic" variables
Normally, when you declare a variable inside a function, it has automatic storage duration. This means the variable is born when the function starts and dies the moment the function reaches its closing curly brace. If you call that function again, the variable is recreated from scratch, completely forgetting whatever happened during the previous call.
The static solution
Sometimes you want a function to have a "memory." You want a variable that belongs to the function but doesn't get wiped out when the function finishes. By adding the static keyword, you change how the variable is stored.
Think of a normal variable like a whiteboard in a meeting room that gets erased every time the meeting ends. A static variable is like a notebook kept in that same room; even if everyone leaves and comes back tomorrow, the notes from the last meeting are still there.
How it looks in code
When you mark a local variable as static, it is initialized only once (when the program starts) and persists for the entire life of the program.
#include <stdio.h>
void incrementCounter() {
// This line only runs once during the entire program life
static int count = 0;
count++;
printf("Current count: %d\n", count);
}
int main() {
incrementCounter(); // Prints: Current count: 1
incrementCounter(); // Prints: Current count: 2
incrementCounter(); // Prints: Current count: 3
return 0;
}
In the example above, if count were a normal variable, it would be reset to 0 every time incrementCounter was called, and the program would just print "1" three times. Because it is static, the variable stays in the computer's memory, holding onto its previous value even while the function isn't running.
Why use it?
Using static inside a function is a great way to maintain state without using "global variables." It keeps your code clean because the variable is only accessible inside the function that needs it, but it provides the persistence needed for tasks like counting hits, generating unique IDs, or caching a result.
Key takeaway
A static local variable is initialized only once and "remembers" its value between successive function calls.