We can say the keyword static acts to extend the lifetime of a variable to the lifetime of the program because the lifetime of a variable is the period over which it exists.
This is true for static
variables defined inside a function like:
int *my_function() {
static int my_static_var[4] = {0,0,0,0};
return my_static_var;
}
Here my_static_var
's lifetime is the lifetime of the program never goes out of scope³, so it's valid to access the memory after the function has returned.
However, all calls to this (my_function
) function will return the exact same block of memory, so conceptually it's really a global variable that can't be accessed directly outside of the function.
Of course, you can also define variables outside a function:
static int my_static_var[4];
Here my_static_var
is only accessible within the same translation unit.
That means another "file" cannot directly² access my_static_var
; it's bound to the file it was defined in.
Also, all globally defined variables are automatically initialized to 0
.¹
Note you cannot declare a static variable, since static variables are intentionally not shared with other parts of your source code. You always have to define (declaration / definition are two different things) it.
The same concept can be applied to static
functions:
static int my_function() {
return 0;
}
Here the function my_function
cannot be accessed directly outside the translation unit it was defined in.
I don't know of any other uses for the static
keyword in C.
¹ The same applies to static
variables defined inside a function.
² It would still be possible through a pointer, for example.
³ Variable goes out of scope, see comment from @Eric Postpischil