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; }
A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With