On local and global static variables in C++

前端 未结 7 1074
野的像风
野的像风 2020-11-29 05:55

C++ Primer says

Each local static variable is initialized before the first time execution passes through the object\'s definition. Local statics are

7条回答
  •  清酒与你
    2020-11-29 06:14

    Hopefully, this example will help to understand the difference between static local and global variable.

    #include 
    
    using namespace std;
    
    static int z = 0;
    
    void method1() {
        static int x = 0;
        cout << "X : " << ++x << ", Z : " << ++z << endl;
    }
    
    void method2() {
        int y = 0;
        cout << "Y : " << ++y << ", Z : " << ++z << endl;
    }
    
    int main() {
        method1();
        method1();
        method1();
        method1();
        method2();
        method2();
        method2();
        method2();
        return 0;
    }
    

    output:

    X : 1, Z : 1
    X : 2, Z : 2
    X : 3, Z : 3
    X : 4, Z : 4
    Y : 1, Z : 5
    Y : 1, Z : 6
    Y : 1, Z : 7
    Y : 1, Z : 8
    

提交回复
热议问题