What static does in C
In C, static has two main jobs, depending on where it appears. Inside a function, it makes a local variable keep its value between calls. Outside any function, it limits a variable or function to the file where it is written. Both of these also work the same way in C++.
A static local variable
A static local variable exists for the whole run of the program, but its name is visible only inside the function. It is set up once, not on every call, so its value carries over from one call to the next. If you do not give it a value, it starts at zero.
Here is a small C program:
#include <stdio.h>
static int total = 0; // file-scope static: visible only in this file
static void add_one(void) {
static int calls = 0; // static local: keeps its value between calls
calls++;
total++;
printf("calls = %d, total = %d\n", calls, total);
}
int main(void) {
add_one(); // prints calls = 1, total = 1
add_one(); // prints calls = 2, total = 2
return 0;
}
The line static int calls = 0; runs only once. Each call adds one to calls, and the next call starts from the stored value. If calls were an ordinary local variable, both calls would print 1.
A static file-scope variable or function
A variable or function declared at file scope, without static, can be used from other source files that declare it. Adding static limits it to the file where it is written. In the example, no other file can see total.
This is also why two files can each have a static function with the same name without clashing. A file-level static function is the case covered in static functions in c, and the rule is the same as for variables. In C++, many programmers use an unnamed namespace for the same purpose.
static inside a C++ class
C has no classes, so this use applies only to C++. Inside a class, static marks a member that belongs to the class instead of to each object. That is a separate use of the keyword from the two jobs above, and the example does not cover it.
When should you use static?
Use static local variables sparingly. A function that keeps hidden state can return different results for the same input, depending on earlier calls, which makes it harder to test and reason about.
Use file-scope static when you want a helper function or variable kept private to one file. This keeps its name from clashing with names in other files.
Common mistakes
- Expecting a static local to reset. Its value persists across calls, so a count keeps growing.
- Putting a static variable in a header. Each source file that includes the header gets its own copy, so the value is not shared between files.
- Assuming static means global. A static local is still visible only inside its function.
The short version
In C, use static inside a function to keep a value between calls, and outside a function to limit a name to its file.