Can I access static variables inside a function from outside

后端 未结 8 1398
夕颜
夕颜 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: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".

提交回复
热议问题