Pay attention to the use of the scope. Generally, a pair of curly braces is used as a scope. For example, a function code:
1 Void Func (void)
2 {
3 Int I = 100;
4 Int Sum = 0;
5 For (int I = 0; I <10; I ++)
6 {
7 Sum + = I;
8}
9 Printf (I); // The printed value is 100, Because I is only a local variable in the for loop.
10}
When a variable is defined in a CPP without any special modifier such as const or static Declaration, for example, int a = 7; it can be accessed by other CPP files compiled at the same time, in these CPP files, the extern modifier must be used to indicate that the variables have been declared and defined elsewhere. The static function of C ++ has two usage methods: static in process-oriented programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes. Declaring and defining static local variables does not allow access to the variable in this file, but is only valid in the function scope. The declared variables are different from other local variables, the value of the variable in the static region of the memory will be retained, for example:
Code
1 void func ()
2 {
3 static int a = 7; // the first time the variable is called for initialization, the value of a is recently changed.
4 a ++;
5 cout <a <endl;
6}
7 int _ tmain (int argc, _ TCHAR * argv [])
8 {
9 func (); // The output a value is 8
10 func (); // The output a value is 9, because the previous function's operations on a are saved.
11 while (true)
12 {
13}
14 return 0;
15
Another function of Static is as mentioned above, so that the variable can only be valid in this CPP file. When Static is used to declare a class member function or variable, the variable is shared by all objects of the class and only one copy exists in the memory, any changes made to the variable will affect the place where the variable is used and cause corresponding changes. In fact, it can save memory space and achieve data sharing among objects.