Okay to declare static global variable in .h file?

后端 未结 6 2006
野趣味
野趣味 2020-12-13 07:36

static keyword keeps the scope of a global variable limited to that translation unit. If I use static int x in a .h file and include that .h file every

6条回答
  •  佛祖请我去吃肉
    2020-12-13 08:18

    If I use static int x in a .h file and include that .h file every other file, won't they all belong to the same translation unit?

    If you declare something as static (not inside a class, for class static keyword has a different semantic), that static variable cannot be seen outside its TU. So putting it in the header file will cause each TU including that header to have a different private copy of that static variable.

    And is a const variable's scope limited to the TU even if it confined in a for loop in the file?

    NO. Even for a static const value, the scope is determined by it's declaration. So the scope will be limited by your for brackets.

提交回复
热议问题