4
In C++ static variables are very important. Let’s assume that I want to make a factorial that uses recursion.
unsigned long long int RecursionFatorial(unsigned int fator)
{
static long long int FatReturn;
if(fator == 0)
{
unsigned long long int FatReturn_ = FatReturn;
FatReturn = 0;
return FatReturn_;
}
else
{
if(FatReturn == 0) FatReturn = 1;
FatReturn *= fator;
RecursionFatorial(fator - 1);
}
}
The code runs and gives the expected result, but the code gets bigger: you need to create new variables (nonstatic) to reset the variables that are static, check if the new is zero to be able to change the value (first call) and cause unnecessary memory occupation. How we should make good use of static variables and then clean them?
In fact, this use you made of static variables is not recommended. If two threads call its function in parallel the result will not be set.
– C. E. Gesser
An interesting curiosity is that the reason FORTRAN 77 did not allow recursion is precisely because the local variables and the return value of the functions were stored in static locations instead of using the stack.
– hugomg