What does “static” mean in C?

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

    People keep saying that 'static' in C has two meanings. I offer an alternate way of viewing it that gives it a single meaning:

    • Applying 'static' to an item forces that item to have two properties: (a) It is not visible outside the current scope; (b) It is persistent.

    The reason it seems to have two meanings is that, in C, every item to which 'static' may be applied already has one of these two properties, so it seems as if that particular usage only involves the other.

    For example, consider variables. Variables declared outside of functions already have persistence (in the data segment), so applying 'static' can only make them not visible outside the current scope (compilation unit). Contrariwise, variables declared inside of functions already have non-visibility outside the current scope (function), so applying 'static' can only make them persistent.

    Applying 'static' to functions is just like applying it to global variables - code is necessarily persistent (at least within the language), so only visibility can be altered.

    NOTE: These comments only apply to C. In C++, applying 'static' to class methods is truly giving the keyword a different meaning. Similarly for the C99 array-argument extension.

提交回复
热议问题