0 day streak
c / intermediate
Snippet

Persistence with Static Variables

Static variables within a function scope are initialized only once and persist their value between function calls. This provides a way to maintain state without polluting the global namespace.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int get_next_id() {
static int counter = 0;
return ++counter;
}
int main() {
printf("%d\n", get_next_id()); // 1
printf("%d\n", get_next_id()); // 2
return 0;
}
Breakdown
1
static int counter = 0;
Declares a variable that retains its value across multiple function executions.
2
return ++counter;
Increments the persistent value and returns it to the caller.