Reputation: 12662
Can I declare a global variable inside a non-member function?
Or in other words, a static equivalent for a non-member function?
And I'd like the variable to not be const - e.g. modifiable...
Upvotes: 1
Views: 173
Reputation: 254461
You can declare a global variable inside a function:
void f() {
extern int i;
}
But you'll also need to define it in the surrounding namespace, if you want to use it.
Being global, the definition doesn't have to be the same translation unit, but is subject to the One Definition Rule.
If, as indicated in the comments, you actually want a persistent local variable, initialised the first time the function is called, then that's exactly how a local static variable behaves:
void f() {
static int i = whatever(); // initialised the first time
i = something_else(); // the new value is preserved for next time
}
Upvotes: 6
Reputation: 208353
Can I declare a global variable inside a non-member function?
You can provide a declaration for a namespace level global variable inside a function. But I have the feeling that you are looking for something else and did not get the wording quite right:
Or in other words, a static equivalent for a non-member function?
You can declare (and define) a local static variable in a function. The lifetime of which will extend beyond the execution of the function (i.e. the variable will be there for the next function execution and so on).
int nextValue() {
static int counter = 0;
return ++counter;
}
Note that this is not a global, as global implies accessibility from any context and this variable is only accessible within nextValue
.
And I'd like the variable to not be const - e.g. modifiable...
This is completely orthogonal to where you declare/define a variable.
Upvotes: 3