Static, define, and const in C

前端 未结 9 2041
半阙折子戏
半阙折子戏 2020-12-13 04:52

I\'ve read that static variables are used inside function when one doesn\'t want the variable value to change/initialize each time the function is called. But what about def

9条回答
  •  轮回少年
    2020-12-13 05:23

    ... change/initialize each time the function is called

    You use the words "change" and "initialize" as though they were the same, but they aren't

    void f(void) {
      static int a = 0;
      a++; // changed!
      printf("%d\n", a);
    }
    
    int main(void) {
      f(); f();
    }
    
    /* 
      # 1
      # 2
    */
    

    When at file-scope (outside functions) static does not mean "const" as in "static value", but it means that the identifier can only be referred to in that translation unit.

    So your first m without const can still be changed. Only const guards against changes. But if you omit static then if you link in a library or another object file that has the same non-static identifier at file-scope you will get conflicts at link-time.

提交回复
热议问题