What does “static” mean in C?

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

    In C, static has two meanings, depending on scope of its use. In the global scope, when an object is declared at the file level, it means that that object is only visible within that file.

    At any other scope it declares an object that will retain its value between the different times that the particular scope is entered. For example, if an int is delcared within a procedure:

    void procedure(void)
    {
       static int i = 0;
    
       i++;
    }
    

    the value of 'i' is initialized to zero on the first call to the procedure, and the value is retained each subsequent time the procedure is called. if 'i' were printed it would output a sequence of 0, 1, 2, 3, ...

提交回复
热议问题