# Lifetime of local static variables

Local static variables are constructed when the program flow first encounters their constructor call. This means that if control does not reach it, they will not be constructed.
They are destroyed at the end of the program. As with all objects, local statics are destroyed in reverse order of their creation.

#include <iostream>
#include <string>

struct Announcer {
Announcer(const std::string& str)
: msg(str)
{
std::cout << "Created " << msg << "\n";
}
~Announcer()
{
std::cout << "Destroyed " << msg << "\n";
}
std::string msg;
};

void func(bool condition)
{
if (condition) {
static Announcer a1("in condition");
}
static Announcer a2("in func");
}

int main(int argc, char *argv[])
{
func(argc > 1);
}


Running this without an argument produces:

Created in func
Destroyed in func


Because the code never enters the conditional in func(), a1 is never created.
Running it with an argument produces:

Created in condition
Created in func
Destroyed in func
Destroyed in condition


Here, the conditional has been entered, so a1 is created. Note the order of the destructor calls – in revese order to the order of construction.