c++functionstaticstatic-variables

In C++, what happens if two different functions declare the same static variable?


void foo() {
    static int x;
}

void bar() {
    static int x;
}

int main() {
    foo();
    bar();
}

Solution

  • They each see only their own one. A variable cannot be "seen" from outside the scope that it's declared in.

    If, on the other hand, you did this:

    static int x;
    
    void foo() {
        static int x;
    }
    
    int main() {
        foo();
    }
    

    then foo() only sees its local x; the global x has been "hidden" by it. But changes to one don't affect the value of the other.