1. Static global variables: Only scope this file, and other files cannot use extern.
File1.c
# Include <stdio. h>
Static int I = 0;
File2.c
# Include <stdio. h>
Extern int I;
Int main (int argc, const char * argv [])
{
Printf ("% d \ n", I );
Return 0;
}
Gcc *. c->
./Tmp/ccftYQ26.o: In function 'main ':
W2.c :(. text + 0xb): undefined reference to 'I'
Collect2: ld returned 1 exit status
/#
2. Static local variables
Because static defined or declared variables are stored in the static zone of the memory, rather than in the stack, after this scope
{
Static int I = 1;
I ++;
}
The variable I will not be destroyed, and it will not be redefined again, but the original value is used, but this scope is partial. that is, a static I is defined in other scopes, and the first static I is not the same memory.
It is worth noting that going into this scope again, static int I = 1; in fact, it only serves as a declaration. It just tells you that this symbol exists. It does not play a value assignment.
See the following program:
Static int j;
Void test (){
Static int I = 1; // equivalent to Declaration
I ++;
Printf ("I = % d \ n", I );
}
Void test2 (){
J = 0; // every time you enter this scope, the value is assigned again.
J ++;
Printf ("j = % d \ n", j );
}
Int main (int argc, const char * argv [])
{
Int k = 0;
For (; k <10; k ++ ){
Test ();
Test2 ();
}
Return 0;
}
3. the modifier function is different from the modifier variable. One thing is the same: it only applies to this file and has nothing to do with the storage method (static storage area ). this is very useful, and it is equivalent to the namespace of C ++!
4. C ++ modifies member variables. All objects share static members.
Class Test {
Public:
Test (int j, int k );
Void GetI () {cout <I <endl ;}
Private:
Int j, k;
Static int I; // static member, non-Global
};
Int Test: I = 0;
Test: Test (int j, int k ){
This-> j = j;
This-> k = k;
I = j + k;
}
Int main (int argc, const char * argv [])
{
Test a (1, 2 );
A. GetI ();
Test B (2, 3 );
B. GetI ();
A. GetI ();
Return 0;
}
5. static member functions
Static member functions cannot call non-static members because they do not have this. Non-static members must be called by objects. because this is not available, there is a slight increase in speed. Of course, static member functions can also be called using objects.
Class Test {
Public:
Test (int j, int k );
Static void GetI () {cout <I <endl ;}
Static void test ();
Private:
Int j, k;
Static int I;
};
Int Test: I = 0;
Test: Test (int j, int k ){
This-> j = j;
This-> k = k;
I = j + k;
}
Void Test: test (){
GetI ();
}
Int main (int argc, const char * argv [])
{
Test a (1, 2 );
A. test ();
Test: test ();
Return 0;
}
6. The default initialization value is 0. Because the static zone contains global variables, the default initialization value is 0.
From Crazybaby's blog