#include <iostream>
usingnamespace std;
int glob; // global, therefore static, therefore initialized to zero
void proc( )
{ staticint 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
}
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
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.
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
staticint 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.