Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access static variables inside a function from outside

Tags:

c++

c

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

#include <iostream>
using namespace std;

void f()
{
    static int count = 3;
    cout << count << endl;
}

int main(int argc, char** argv)
{
    f::count = 5;   // apparently this is an invalid syntax.
    f();

    return 0;
}
like image 335
Robin Hsu Avatar asked Jun 04 '15 05:06

Robin Hsu


People also ask

Can we access a static variable declared inside a static method outside that method?

Static variables in methods i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.

Can I access variable inside static function?

We cannot access non-static variables or instance variables inside a static method. Because a static method can be called even when no objects of the class have been instantiated.

Can we access private static variable outside class?

private static variable is shared, but not accessible outside the class. public non-static variable is not shared, but accessible outside the class. private non-static variable is neither shared nor accessible outside the class.

Can static variables be accessed outside the class C++?

Static Function MembersA static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class.


2 Answers

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".

like image 80
rici Avatar answered Sep 20 '22 18:09

rici


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

like image 31
Glenn Teitelbaum Avatar answered Sep 21 '22 18:09

Glenn Teitelbaum