What does “static” mean in C?

后端 未结 19 1990
误落风尘
误落风尘 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:45

    Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

    Look at this for example - A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

    #include 
    int fun() 
    { 
      static int count = 0; 
      count++; 
      return count; 
    } 
    
    int main() 
    { 
      printf("%d ", fun()); 
      printf("%d ", fun()); 
      return 0; 
    }
    

    This will output: 1 2

    As 1 stays in the memory as it was declared static

    Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.

    #include  
    int main() 
    { 
        static int x; 
        int y; 
        printf("%d \n %d", x, y); 
    }
    

    This will output : 0 [some_garbage_value]

    These are the major ones I found that weren't explained above for a newbie!

提交回复
热议问题