There are four storage classes for C ++ variables:
Auto corresponding to the automatic class;
Register class corresponds to register;
The external class corresponds to extern;
Static classes (including internal static classes and external static classes) correspond to static;
1. Automatic class and register class
Both automatic variables and register variables are local variables. You can add auto or not when defining or describing automatic variables, but you must add register to define register variables; register variables are usually stored in General registers of the CPU. She only tells the compiler that the variables should be stored in High-Speed registers to increase the execution speed. However, the register declaration is only a "suggestion" to the compiler, not a mandatory requirement.
The scope and existence of automatic variables and register variables are consistent, "same storage and elimination ";
There is no default value after the definition and description of automatic classes and register variables. It can only be used after initialization or assignment.
2. external variables
The scope of an external variable is the largest. Its scope is the whole program. The definition and description of an external variable are two different things, which are a feature of this variable. An external class variable can be defined only once in a program, but it can be described multiple times. When defining external class variables, you do not need to add any storage class specifiers. You only need to write them in the function body. However, you must add the specifier extern before reference. As follows:
# Include <iostream>
Using namespace STD;
Extern int x = 1 // external class variable
Void M ()
{
X = x + 1;
Cout <x <Endl;
}
Void N ()
{
X = X-1;
Cout <x <Endl;
}
Void main ()
{
Int x = 0;
Cout <x <Endl;
M ();
N ();
Cout <x <Endl;
}
Running result:
3. Static variables-see here
An example can be provided from Baidu. You can study it carefully.
# Include <iostream>
Using namespace STD;
Int n = 1;
Void func ();
Void main ()
{
Static int x = 5;
Int y; y = N;
Cout <"Main:" <x <"" <Y <"" <n <Endl; // output main static local X = 5, main local y = 1, global n = 1
// Result: Main: 511
Func (); // output func static local X = 4 + 2 = 6, local variable Y = 10 + 11 = 21, global n = 1 + 10 = 11
// Result FUNC: 62111
Cout <"Main:" <x <"" <Y <"" <n <Endl; // both X and Y are the same as the first comment, but the global N is changed to 11.
// Result: Main: 5111
Func (); // output func static local X = 6 + 2 = 8, local variable Y = 10 + 21 = 31, global n = 11 + 10 = 21
// Result FUNC: 83121
}
Void func ()
{
Static int x = 4; int y = 10;
X = x + 2; n = N + 10; y = Y + N;
Cout <"FUNC:" <x <"" <Y <"" <n <Endl;
}