Use of static variables and functions in global scope

后端 未结 3 1280
半阙折子戏
半阙折子戏 2021-01-07 17:38

Is there a use for flagging a variable as static, when it lies in the global scope of a .cpp file, not in a function?

Can you use the static keyword for

3条回答
  •  旧时难觅i
    2021-01-07 18:22

    Yes, if you want to declare file-scope variable, then static keyword is necessary. static variables declared in one translation unit cannot be referred to from another translation unit.


    By the way, use of static keyword is deprecated in C++03.

    The section $7.3.1.1/2 from the C++ Standard (2003) reads,

    The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.

    C++ prefers unnamed namespace over static keyword. See this topic:

    Superiority of unnamed namespace over static?

提交回复
热议问题