What does “static” mean in C?

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

    static means different things in different contexts.

    1. You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.

      void foo ()
      {
      static int i = 0;
      printf("%d", i); i++
      }
      
    2. Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.

      static void foo() { ... }
      

提交回复
热议问题