C
static
Learn file-local variables and functions with static.
The static keyword
static has two meanings. At file scope (outside functions), it makes a variable or function file-local; another .c file can't see it even with extern. Inside a function, it extends the variable's lifetime to the whole program but keeps scope the same.
Example: static int internal_counter = 0; in one .c file is visible only there. This hides a module's implementation detail; the header exposes only the public API, internal helpers are static. This technique is called internal linkage.
static inside a function
Inside a function, static int calls = 0; makes calls keep its value across calls. On the first call it's initialized to zero; later calls keep the previous value. A normal local would reinitialize each call.
Example: int next_id(void) { static int id = 0; return ++id; }. Each call returns one more than before. This pattern fits counters and caches. It's not thread-safe though; use carefully in multi-threaded programs. The lifetime is the whole program, but scope stays inside the function; not accessible from outside.
Exercise Write a static counter
Write int next_id(void) with static int id = 0; and return ++id; inside. In int main(void) add printf("%d \n", next_id()); and printf("%d\n", next_id());. Don't forget <stdio.h>.
Show example solution
#include <stdio.h>
int next_id(void) {
static int id = 0;
return ++id;
}
int main(void) {
printf("%d \n", next_id());
printf("%d\n", next_id());
return 0;
}
Test yourself
-
Match static usages
- File-scope static
- Internal linkage
- Function-scope static
- Persistent lifetime
- extern
- Cross-file sharing
- Header
- Public API
-
Complete the counter function
int next_id(void) {
____ int id = 0;
return ++id;
}
Show answer
int next_id(void) {
static int id = 0;
return ++id;
}
-
What does a file-scope static variable do?
- Becomes visible from other files
- Stays visible only in its file
- Auto-resets
- Gives program-long lifetime
Show answer
Stays visible only in its file — File-scope static gives internal linkage.
Next lesson: Makefile basics