C++ Primer says
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.
Are local static variables any different from global static variables? Other then the location where they are declared, what else is different?
void foo () {
static int x = 0;
++x;
cout << x << endl;
}
int main (int argc, char const *argv[]) {
foo(); // 1
foo(); // 2
foo(); // 3
return 0;
}
compare with
static int x = 0;
void foo () {
++x;
cout << x << endl;
}
int main (int argc, char const *argv[]) {
foo(); // 1
foo(); // 2
foo(); // 3
return 0;
}
There real name is:
Global variables are also 'static storage duration object'. The major difference from global variables are:
Note: An exception during construction means they were not initialized and thus not used.
So it will re-try the next time the function is entered.
(ie they can not be seen outside the function)
Apart from that they are just like other 'static storage duration objects'.
Note: Like all 'static storage duration objects' they are destroyed in reverse order of creation.
The differences are:
The second difference can be useful to avoid the static intialisation order fiasco, where global variables can be accessed before they're initialised. By replacing the global variable with a function that returns a reference to a local static variable, you can guarantee that it's initialised before anything accesses it. (However, there's still no guarantee that it won't be destroyed before anything finishes accessing it; you still need to take great care if you think you need a globally-accessible variable. See the comments for a link to help in that situation.)
Hopefully, this example will help to understand the difference between static local and global variable.
output:
In your first code block, x is local to the foo() function which means that it is created in foo() and destroyed at the end of the function after cout. However, in your second block x is global which means that the scope of x is the entire program. If you wanted to under int main your could cout << x << endl and it would print however, in the first block it would say x not declared
Their scope is different. A global-scoped static variable is accessible to any function in the file, while the function-scoped variable is accessible only within that function.