Programs & Examples
C Variables · Study material
Unique ID generator with a static local
A static local remembers the last value handed out, so every call returns a new ID – and no other code can tamper with the counter.
#include <stdio.h>
int next_employee_id(void) {
static int last = 1000; /* remembers the last ID between calls */
return ++last;
}
int main(void) {
for (int i = 0; i < 3; i++)
printf("EMP-%d ", next_employee_id());
printf("\n");
return 0;
}
EMP-1001 EMP-1002 EMP-1003
Running average with static state
Two static locals keep the sum and count between calls; each call returns the average so far.
#include <stdio.h>
double running_average(double value) {
static double sum = 0; /* both keep their values across calls */
static int count = 0;
sum += value;
count++;
return sum / count;
}
int main(void) {
double readings[] = {10, 20, 60};
for (int i = 0; i < 3; i++)
printf("after %.0f: %.1f\n", readings[i], running_average(readings[i]));
return 0;
}
after 10: 10.0 after 20: 15.0 after 60: 30.0