"There are some things you can’t do with automatic variables within a function. You can’t count how many times a function is called, for example, because you can’t accumulate a value from one call to the next. There’s more than one way to get around this if you need to. For instance, you could use a reference parameter to update a count in the calling program, but this wouldn't help if the function was called from lots of different places within a program."
How will it not help if the function is called from many places in the program?
Is it because maybe the scope of the variable used will end?
void staticFunction( void )
{
staticshort calls = 0; //static is only initialized once kind of like a global
calls++;
std::cout << "This function has been called " << calls << " times!" << std::endl;
}
void autoFunction( void )
{
short calls = 0; //gets initialized each time
calls++;
std::cout << "This function has been called " << calls << " times!" << std::endl;
}
int main( int argc , char** argv )
{
for( unsignedint i = 0; i < 10; i++ )
{
staticFunction();
}
for( unsignedint i = 0; i < 10; i++ )
{
autoFunction();
}
}
I'm not sure exaclty what he means maybe he means like it will seem like it jumps if it is called a bunch of times in different functions at one time maybe?
void funky(int &count){
count++;
std::cout << "I have been called " << count << " times so far..." << std::endl;
}
void funky2(){
int callnumber(0);
for(int I=0; I < 20; I++) funky(callnumber);
}
void funky3(){
int callnumber(0);
for(int I=0; I < 5; I++) funky(callnumber);
}
So what is the total number of times funky has been called? Is it 20? 5? Or 25?
Without using static variables, the message printed out from funky is misleading.