Static variables

In the below example, why is statloc not reinitialised and is it incremented in the last call to void proc()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 #include <iostream>

using namespace std;

int glob;                  // global, therefore static, therefore initialized to zero

void proc( )
{  static int statloc = glob;  
   int autoloc = 3; 
   cout << autoloc << " " << statloc << endl;
   statloc++; autoloc++;   // incrementing of autoloc is pointless; it is about to disappear
}

int main( )
{  cout << glob << endl;   // glob is zero
   glob = 5;   
   cout << glob << endl;   // glob is 5 
   proc();                 // statloc is 5, autoloc is 3, statloc increased to 6 
   glob = 8;
   cout << glob << endl;   // glob is 8
   proc();                 // statloc still 6 - it is not reinitialized 
}
It isn't incremented. Why not?
because it is a static when you do static int a = something it only does that once. if you wish to reassign a value each time the function is called then get rid of the statloc++ and put statlocc = something. and global variables are bad to use
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void staticFunction( void )
{
    static unsigned int staticNumber = 0;
    unsigned int autoNumber = 0;
    std::cout << "Static Number: " << staticNumber << std::endl;
    std::cout << "Auto Number: " << autoNumber << std::endl;
    staticNumber++;
    autoNumber++;
}

int main( int argc , char** argv )
{
    for( unsigned int i = 0; i < 10; i++ )
    {
        staticFunction();
    }
    return( 0  );
}
Static Number: 0
Auto Number: 0
Static Number: 1
Auto Number: 0
Static Number: 2
Auto Number: 0
Static Number: 3
Auto Number: 0
Static Number: 4
Auto Number: 0
Static Number: 5
Auto Number: 0
Static Number: 6
Auto Number: 0
Static Number: 7
Auto Number: 0
Static Number: 8
Auto Number: 0
Static Number: 9
Auto Number: 0

Process returned 0 (0x0)   execution time : 0.205 s
Press any key to continue.

Last edited on
Static variables can only be declared once, so your initialization with glob also only occurs once. To reassign glob to statloc each time proc() is called, try:
1
2
static int statloc; //Only occurs once
   statloc = glob; //Assignment, not declaration instruction 


It isn't incremented. Why not?

Take a close look at the value of statloc that printed out. It is 6, which is the incremented value of 5, which you initialized statloc with. In the second call at the end of your main function, statloc is printed out again before it is incremented.

-first call to proc
--statloc = 5 (initialization)
--print statloc (5)
--statloc++ --> statloc = 6

-second call to proc
--statloc = 8 (ignored because static variable has been declared already)
--print statloc (6)
--statloc++ --> statloc = 7
So it is incremented and static variables can only be initialised once but can be assigned on numerous occasions. Thanks a lot.
Last edited on
Topic archived. No new replies allowed.