What does “static” mean in C?

后端 未结 19 1910
误落风尘
误落风尘 2020-11-21 05:18

I\'ve seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?

19条回答
  •  无人共我
    2020-11-21 05:46

    In C programming, static is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable's lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:

    #include 
    int counterFunction() 
    { 
      static int count = 0; 
      count++; 
      return count; 
    } 
    
    int main() 
    { 
      printf("First Counter Output = %d\n", counterFunction()); 
      printf("Second Counter Output = %d ", counterFunction()); 
      return 0; 
    }
    

    Above program will give us this Output:

    First Counter Output = 1 
    Second Counter Output = 1 
    

    Because as soon as we call the function it will initialize the count = 0. And while we execute the counterFunction it will destroy the count variable.

提交回复
热议问题