In C ++ static variables are very important. Let's suppose 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 have to create new variables (not static) to be able to reset variables that are static, check if the new one is zero to change the value (first call ) and causes unnecessary memory occupancy. How should we make good use of static variables and then clean them?