Statically scoped variables have a lifetime of the entire application run, they are set up when the application starts and destroyed when the application stops. There are two types of statically scoped variables, global and static and they are handled very differently.
Global Variables
The first type of statically scoped variable is the global variable. They are declared outside of any function and are available everywhere in the program, after they have been declared. It is generally considered a bad idea to use global variables as they can be changed anywhere which can lead to subtle, hard to track down bugs. It is possible to declare global variables as const and this makes them safe to be used as they can’t be changed anywhere.
#include <iostream>
// Change a to const and it becomes safe.
int a {};
void do_something() {
std::cout << "Doing something" << std::endl;
++a;
}
int main() {
do_something();
std::cout << "The value of a is " << a << std::endl;
return 0;
}
Static Variables
The more interesting of the statically scoped variables is the static variable. Unlike the global variable, this is declared in and scoped to a function. Like the global variable, it lives for the entire run of the application. This means they survive across multiple calls to the function they are defined in and the first time the function is called they are initialized. Thereafter they retain their value.
#include <iostream>
void do_something() {
static int a {};
++a;
std::cout << a << std::endl;
}
int main() {
for (int i {}; i < 5; ++i) {
do_something();
}
return 0;
}