Static Variables

From my book


"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?
I think it means if you call the function from within another function, it might not be possible to pass the same variable to the function.
No but you are taking it as a reference, you should be able to.
maybe he means that you can actually keep track of the number of times a function is called by using a static variable try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void staticFunction( void )
{
    static short 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( unsigned int i = 0; i < 10; i++ )
    {
        staticFunction();
    }

    for( unsigned int 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?
Last edited on
Also he means without it being static, without calls being static lol.
Oh ya I wasn't really reading it all I.just saw static
1
2
3
4
5
6
7
8
9
10
11
12
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.
Registered users can post here. Sign in or register to post.