Why declare a variable or function static in C?

前端 未结 4 1795
小鲜肉
小鲜肉 2020-12-18 19:25

I understand what static does, but not why we use it. Is it just for keeping the abstraction layer?

4条回答
  •  执念已碎
    2020-12-18 19:47

    There are a few reasons to use static in C.

    When used with functions, yes the intention is for creating abstraction. The original term for the scope of a C source code file was "translation unit." The static functions may only be reached from within the same translation unit. These static functions are similar to private methods in C++, liberally interpreted (in that analogy, a translation unit defines a class).

    Static data at a global level is also not accessible from outside the translation unit, and this is also used for creating an abstraction. Additionally, all static data is initialized to zero, so static may be used to control initialization.

    Static at the local ("automatic") variable level is used to abstract the implementation of the function which maintains state across calls, but avoids using a variable at translation unit scope. Again, the variables are initialized to zero due to static qualification.

提交回复
热议问题