As you may know, a local static variable cannot be accessed outside the function by name but can be accessed via pointer or reference to it. So the code below is well-formed.
But why? I know this fact as a fact, but have no ground. Actually what I want is the related excerpt from C++ standard. I'm reading it but not end up finding the evidence. Could anyone please give me the excerpt or a hint to find that (because just searching "static" in the document results in over a hundred of hits)?
#include <iostream>
using namespace std;
class Test {
public:
int * f(int i) const {
static int j;
j += i;
cout << "now j = " << j << "\n";
return &j;
}
int & g(int i) const { //same as above but handle reference
static int k;
k += i;
cout << "now k = " << k << "\n";
return k;
}
};
int main() {
Test t;
int *p = t.f(3); //=> "now j = 3"
*p += 10;
t.f(0); //=> "now j = 13"
int &r = t.g(3); //=> "now k = 3"
r += 10;
t.g(0); //=> "now k = 13"
}
I took a look at all of the about 20 questions suggested by stack overflow, but have no answer yet. (There was only one related question: Can I access static variables inside a function from outside.)
For the future readers (or just my note):
As indicated in the comment, the same applies to the case of a class member even if it is distant and private
.
#include <iostream>
using namespace std;
class Base {
private:
int i = 0;
public:
int * return_pointer() { return &i; }
void print() { cout << "i = " << i << "\n"; }
};
class Derived : public Base {
public:
int * return_pointer() { return Base::return_pointer(); }
};
int main() {
Derived d;
d.print(); //=> "i = 0"
int *p = d.return_pointer();
*p = 300;
d.print(); //=> "i = 300"
}