Use of static variables and functions in global scope

后端 未结 3 1284
半阙折子戏
半阙折子戏 2021-01-07 17:38

Is there a use for flagging a variable as static, when it lies in the global scope of a .cpp file, not in a function?

Can you use the static keyword for

3条回答
  •  死守一世寂寞
    2021-01-07 18:44

    Taking as an example -

    // At global scope
    int globalVar; // Equivalent to static int globalVar;
                   // They share the same scope
                   // Static variables are guaranteed to be initialized to zero even though
                   //    you don't explicitly initialize them.
    
    
    // At function/local scope
    
    void foo()
    {
        static int staticVar ;  // staticVar retains it's value during various function
                                // function calls to foo();                   
    }
    

    They both cease to exist only when the program terminates/exits.

提交回复
热议问题