Lately I tried getting my head around the static keyword and here I attempt to simply use the static keyword for a variable declaration within a function. Like so:
void counter()
{
static int counter = 0; //should be initialized only once and once only
counter++; //increment for every call of this function
}
I understand that due to the variable being static, it will live outside the function and therefore from wherever I decide to print out counter, it should give me the number of times the function counter()
was called. So I did a simple test as shown:
int main()
{
for(unsigned int i = 0; i < 10; i++){
counter();
}
std::cout << counter << std::endl;
return 0;
}
From this test I expected to get number 10... but instead the number of counts the code returned was 1.
Please, what am I missing here?
I found other submissions to "similar" issues such as this one: static counter in c++ But they mostly revolve around the static keyword being used in classes.