Previous: Import, Up: Programming
Static qualifiers allocate the memory address of a variable in a higher enclosing scope.
For a function body, the variable is allocated in the block where the function is defined; so in the code
struct s {
int count() {
static int c=0;
++c;
return c;
}
}
there is one instance of the variable c for each
object s (as opposed for each call of count).
Similarly, in
int factorial(int n) {
int helper(int k) {
static int x=1;
x *= k;
return k == 1 ? x : helper(k-1);
}
return helper(n);
}
there is one instance of x for every call to
factorial (and not for every call to helper), so this is
a correct, but ugly, implementation of factorial.
Similarly, a static variable declared within a structure is allocated in the block where the structure is defined. Thus,
struct A {
struct B {
static pair z;
}
}
creates one object z for each object of type A created.
In this example,
int pow(int n, int k) {
struct A {
static int x=1;
void helper() {
x *= n;
}
}
A operator init() {return new A;}
for (int i=0; i < k; ++i) {
A a;
a.helper();
}
return A.x;
}
there is one instance of x for each call to pow, so this
is an ugly implementation of exponentiation.