Can I access static variables inside a function from outside

后端 未结 8 1342
夕颜
夕颜 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:29

    As it was said in other answers, there's no such a thing as a special syntax for accessing local variables externally, but you can achieve this by returning a reference to the variable, for instance:

    #include <iostream>
    using namespace std;
    int& f(void)
    {
         static int count = 3;
         cout << count << endl;
    
         return count;
    }
    
    int main()
    {
        int &count = f(); // prints 3
        count = 5;
        f();              // prints 5
        return 0;
    }
    

    In C++11 you can also access your local static variables from a returned lambda:

    #include <iostream>
    #include <functional>
    
    using namespace std;
    
    std::function<void()> fl()
    {
        static int count = 3;
        cout << count << endl;
    
        return []{count=5;};
    }
    
    int main()
    {
        auto l = fl();  // prints 3
        l();
        fl();           // prints 5
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-02 04:29

    No, static variable has its scope limited to block in which it is defined, while its life time is though out the process, so as variable is defined in function it will get into existence once this method is called but in order access it we need to be in function scope.

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

    In C and C++ languages, the scope in which the variable defined is important. You cant reach a variable from upper scopes.

    For this purpose you can use structs or C++ classes and keep this data in the objects.

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

    Variables inside a function scope cannot be accessed externally by name, but you can return a pointer or reference to it

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

    No, you can't, neither in C nor in C++.

    If you want to maintain state associated with a function, define a class with the appropriate state and a member function. (In C++. You've also tagged the question with C; the same technique works but you need to do all the groundwork yourself.)

    Although they have their uses, most of the time non-const static locals are a bad idea. They make your function thread-unsafe, and they often make it "call-once".

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

    A static variable has a scope within the block but it has a lifetime of throughout the program so you cant access the coun tvariable try returning a pointer from the function.

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