static
is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static
is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i
will be preserved between calls to f()
. Other storage classes are the default auto
(but beware the change in meaning in C++11), extern
, and register
, plus thread_local
in C11/C++11.
At file scope (or namespace scope in C++), static
is a linkage specifier. Functions and variables marked static
in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c
file. This usage of static
was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static
can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a
must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!