The following example shows how a variable declared static in a function retains its state between calls to that function.
// static1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void showstat( int curr ) {
static int nStatic; // Value of nStatic is retained
// between each function call
nStatic += curr;
cout << "nStatic is " << nStatic << endl;
}
int main() {
for ( int i = 0; i < 5; i++ )
showstat( i );
} nStatic is 0
nStatic is 1
nStatic is 3
nStatic is 6
nStatic is 10
The following example shows the use of static in a class.
// static2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class CMyClass {
public:
static int m_i;
};
int CMyClass::m_i = 0;
int main() {
cout << CMyClass::m_i << endl;
cout << CMyClass::m_i << endl;
CMyClass::m_i = 1;
cout << CMyClass::m_i << endl;
cout << CMyClass::m_i << endl;
} The following example shows a local variable declared static in a member function. The static variable is available to the whole program; all instances of the type share the same copy of the static variable.
Note: |
|---|
| Assigning a value to a static local variable in a multithreaded application is not thread safe and we do not recommend it as a programming practice. |
// static3.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
struct C {
void Test(int value) {
static int var = 0;
if (var == value)
cout << "var == value" << endl;
else
cout << "var != value" << endl;
var = value;
}
};
int main() {
C c1;
C c2;
c1.Test(100);
c2.Test(100);
} var != value
var == value