C/C++: Can I access static variables inside a function from outside? For example:
#include
using namespace std;
void f()
{
static int c
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.
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.