What does “static” mean in C?

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

    I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".

    In short, the word static is used with two meanings:

    1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
    2. But, when the static keyword (big emphasis on it being used in code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern keyword, which gives an object external linkage.

    Peter Van Der Linden gives these two meanings in "Expert C Programming":

    • Inside a function, retains its value between calls.
    • At the function level, visible only in this file.

提交回复
热议问题