Example 1 — A static counter for unique IDs
Each call continues from the previous value.
#include <stdio.h>
int next_id(void) {
static int id = 0;
return ++id;
}
int main(void) {
for (int i = 0; i < 3; i++) {
printf("id %d\n", next_id());
}
return 0;
} How It Works
static int id = 0;runs its initializer once, beforemain.- Each call increments the same stored value.
- No global variable is needed, so nothing else can change
id.
