Static variables in C++
I ran into a interesting issue today. Check out this pseudo-code:
void Loop()
{
static int x = 1;
printf("%d", x);
x++;
}
void main(void)
{
while(true)
{
Loop();
}
}
Even though x is static, why doesn't this code just print "1" every time? I am reinitializing x to 1 on every iteration before I print it. But for whatever reason, x increments开发者_开发技巧 as expected.
The initialization of a static variable only happens the first time. After that, the instance is shared across all calls to the function.
I am reinitializing x to 1 on every iteration
No, you're not: you're initializing it to 1, but it only gets initialized once.
static
doesn't mean const
.
From MSDN:
When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).
A variable declared static in a function retains its state between calls to that function.
When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.
The value of static is retained between each function call, so for example (from MSDN again):
// 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 );
}
In your example, x will increment as expected because the value is retained.
static in this context means that value should be retained between calls to the function. the initialization is done only once.
精彩评论