Are all variables in a static function static by default?
No, the only condition for creating a static variable in C ++ is the static
keyword .
For example, if you change Foo
to:
static void Foo()
{
int bar = 0;
bar++;
cout << bar << endl;
}
And then call:
Foo(); Foo();
Since bar
it is not static, the output will be:
1
1
If you declare bar
like static
this:
static void Foo()
{
static int bar = 0;
bar++;
cout << bar << endl;
}
In fact, your output will be:
1
2
source to share
No, variables inside static functions are allocated in automatic storage by default.
static
functions and variables static
are orthogonal concepts that are used to reuse the same keyword in C and C ++ syntax
- Function execution
static
tells the compiler to hide it from functions defined in other translation units - Creating a variable
static
tells the compiler to place the data for that variable in static storage.
Usage static
for functions has nothing to do with static storage.
source to share