Can I access static variables inside a function from outside

后端 未结 8 1343
夕颜
夕颜 2021-01-02 04:15

C/C++: Can I access static variables inside a function from outside? For example:

#include 
using namespace std;

void f()
{
    static int c         


        
相关标签:
8条回答
  • 2021-01-02 04:53

    No, The variable count is only available inside function and has no linkage. However the lifetime of this variable would be the scope of the file, as C++ Primer suggests

    Each local static variable is initialized before the first time execution passes through the object's definition. Local statics are not destroyed when a function ends; they are destroyed when program terminates.

    0 讨论(0)
  • 2021-01-02 04:53

    No, but (obviously) you can always move it outside of the function so it becomes accessible for the whole file; except for cluttering file-level name space (which is IMHO not a big deal), I don't see much downsides for such a move (and it will be more explicit and obvious too: rather than making access to a supposedly private thing, you'll make it clear that this thing is to be shared).

    That being said, all kinds of non-const static data should be used with extreme care, and a rule of thumb (i.e. until proven otherwise) it is that they're a Bad Idea.

    0 讨论(0)
提交回复
热议问题