The static
storage class specifier has three different meanings.
Gives internal linkage to a variable or function declared at namespace scope.
// internal function; can't be linked to
static double semiperimeter(double a, double b, double c) {
return (a + b + c)/2.0;
}
// exported to client
double area(double a, double b, double c) {
const double s = semiperimeter(a, b, c);
return sqrt(s*(s-a)*(s-b)*(s-c));
}
Declares a variable to have static storage duration (unless it is thread_local
). Namespace-scope variables are implicitly static. A static local variable is initialized only once, the first time control passes through its definition, and is not destroyed every time its scope is exited.
void f() {
static int count = 0;
std::cout << "f has been called " << ++count << " times so far\n";
}
When applied to the declaration of a class member, declares that member to be a static member.
struct S {
static S* create() {
return new S;
}
};
int main() {
S* s = S::create();
}
Note that in the case of a static data member of a class, both 2 and 3 apply simultaneously: the static
keyword both makes the member into a static data member and makes it into a variable with static storage duration.