static function/variable

前端 未结 3 1642
太阳男子
太阳男子 2021-01-28 01:28

i just started programming in c++ this concept of static variable/function wasn\'t clear to me..why is this used and is there any other alternative of this!!!

3条回答
  •  [愿得一人]
    2021-01-28 01:34

    The static keyword specifies that the life-time of the given the variable, function or class is application-wide. Like having a single instance.

    This example might illustrate it:

    #include 
    using namespace std;
    
    void test() {
      static int i = 123;
      if (i == 123) {
        i = 321;
      }
      cout << i << endl;
    }
    
    int main(int arg, char **argv) {
      test();
      test();
      return 0;
    }
    

    The output is:

    321

    321

    So "i" is only initialized the first time it is encountered, so to speak. But actually it's allocated at compile time for that function. Afterwards, it's just in the scope of the function test() as a variable, but it is static so changing it changes it in all future calls to test() as well.

    But I encourage you to read more about it here: http://www.cprogramming.com/tutorial/statickeyword.html

提交回复
热议问题