Static Variables In C And C++ – Function Level
We’ve looked at file level static variables, so now let’s see what happens when you put them in a function.
If you declare a static variable at function level (i.e. inside an normal function, not a class method), then you are creating a variable that will:
a) be instantiated the first time the function is actually called, and
b) retain its value after the function exits.
The variable is only accessible inside the function it is declared in.
This is probably the simplest static variable case, and we can see an example of this below:
#include <iostream> #include <time.h> #include <unistd.h> void Defrag(); int main() { Defrag(); sleep(2); Defrag(); } void Defrag() { std::cout << "\tStarting defragmentation." << std::endl; time_t now; time(&now); static time_t LastDefrag = 0; // change this to 1 to see defrag run twice if (now - LastDefrag > 3600) { LastDefrag = now; std::cout << "\tDefragmenting..." << std::endl; } else { std::cout << "\tAlready running. Try later." << std::endl; } }
When we run this code, the output is:
In the code above, the Defrag function contains a local, static, time_t variable which stores the last time this function was called.
The first time the function is called, the static time_t variable (LastDefrag) is created and set to zero. That variable is subsequently set to the system time if a condition is met: namely that the elapsed time period since the last call of Defrag is greater than one hour.
When the main function calls Defrag again, it ignores the creation and initialisation of the static time_t variable. It simply makes the comparison for time passed, and (given we’ve only waited a couple of seconds between calls) the condition is not met and defragmentation is not commenced.
You can verify that this variable is working correctly by changing the function to test for a difference of greater than 1 second (instead of 1 hour, which is the 3600 seconds you see in the code).
When you make this change, the Defrag command will run twice because the time difference is greater than stipulated.
And that’s all there is to it. Function level static variables are definitely the nicest of them all.