const and static
static, used on a local variable, means it's initialized only once and keeps its value between calls — unlike a normal local variable, which is recreated from scratch every time its function runs.
main.c
Try it yourself →#include <stdio.h>
void increment() {
static int count = 0;
count++;
printf("%d\n", count);
}
int main() {
increment();
increment();
increment();
return 0;
}Output
1 2 3
const: a promise the compiler enforces
const marks a variable as unmodifiable after initialization — and unlike a comment or a naming convention, the compiler actually enforces it. This is genuinely what gcc reports — captured from a real run, not written to look plausible:
main.c
Try it yourself →#include <stdio.h>
int main() {
const int max = 100;
max = 200;
printf("%d\n", max);
return 0;
}Output
main.c: In function ‘main’:
main.c:5:9: error: assignment of read-only variable ‘max’
5 | max = 200;
| ^Next: error handling in C — why there are no exceptions, and the return-code convention C uses instead.
Practice exercise
Write a function increment() with a static int count starting at 0 that adds 1 to it and prints it. Call increment() three times.