All variables in C language have their own scopes. The types of declarative variables are different, and their scopes are also different. Variables in C language can be divided into local variables and global variables according to the scope.
I. Local Variables
Local variables are also called internal variables. Local variables are defined in the function. Its scope is limited to the function. It is invalid to use this variable after leaving the function.
For example:
Int F1 (int A)/* function F1 */ { Int B, C; ...... } |
Int F2 (int x)/* function F2 */ { Int y, z ;; ...... } |
Three variables are defined in F1. A is the form parameter, B, and C are the general variables. Variables A, B, and C are valid in the range of F1, or A, B, and C are limited to F1. |
Three variables are defined in F2. X is the form parameter, and Y and Z are the general variables. In the range of F2, the variables X, Y, and Z are valid, or the scope of the variables X, Y, and Z is limited to F2. |
The scope of local variables should also be described as follows:
The variables defined in the main function can only be used in the main function, and cannot be used in other functions. In addition, the main function cannot use variables defined in other functions. Because the main function is also a function, it is in parallel with other functions.
The parameter variable is a local variable of the called function, and the real variable is a local variable of the main function.
The same variable names can be used in different functions. They represent different objects, assign different units, and do not interfere with each other. Although the same variable name can be used in different functions, it is not recommended to use the same variable name in different functions to make the program clear and understandable.
Ii. Global Variables
Int A, B;/* external variable */ Void F1 ()/* function F1 */ { ...... } |
Float X, Y;/* external variable */ Int FZ ()/* function FZ */ { ...... } |
Global variables, also known as external variables, are defined outside the function. Which function does not belong to? It belongs to a source program file. Its scope is the entire source program. Use global variables in functions. Only global variables described in the function can be used. The description of the global variable is extern. However, the global variables defined before a function are not described in this function. For example:
From the above example, we can see that a, B, X, and Y are all external variables defined outside the function, and they are all global variables.
Global variables are described as follows:
The definitions and descriptions of local variables are not distinguished. For external variables, the definition of external variables is not the same as that of external variables. External variables must be defined only once outside of all functions. The general form is: [extern] type specifier variable name, variable name... The extern in square brackets can be omitted without writing.
Example: int A, B;
It is equivalent:
Extern int A, B;
The external variable description appears in each function to use the external variable, and may appear multiple times in the entire program. The general form of the external variable description is: extern type specifier: variable name, variable name ,...; The external variable has been assigned a memory unit during definition. The external variable definition can be used as an initial value. The external variable description cannot be assigned an initial value, but indicates that an external variable must be used in the function.
External variables can enhance the data connection between function modules, but make the function depend on these variables, thus reducing the independence of the function. From the modular program design point of view, this is unfavorable, so do not use global variables whenever necessary.
In the same source file, global variables and local variables are allowed to have the same name. Global variables do not work within the scope of local variables.
int vs(int l,int w) { extern int h; int v; v=l*w*h; return v; } main() { extern int w,h; int l=5; printf("v=%d",vs(l,w)); } int l=3,w=4,h=5;
In this example, the external variables are defined at the end, so the external variables to be used must be described in the previous function. The form parameters of the external variables L, W and vs functions L, W have the same name. All external variables are assigned an initial value, and the mian function also assigns an initial value to L. When executing the program, call the vs function in the printf statement. The value of the real parameter l should be the L value defined in main, which is equal to 5. The external variable L does not work in main; the value of the real parameter W is 4 of the external variable W. after entering the vs parameter, these two values are transmitted to the form parameter l. The H used in the WVS function is an external variable and its value is 5, therefore, the calculation result of V is 100, which is output after the main function is returned.
The storage type of variables determines the different scopes of various variables. The so-called storage type refers to the way variables occupy memory space, also known as storage. Variable storage methods can be divided into static storage and dynamic storage.
Static storage variables are usually divided into storage units during variable definition and remain unchanged until the entire program ends. A Dynamic Storage variable is allocated to a storage unit during execution of a program. It is released immediately after use. A typical example is the form parameter of a function. When a function is defined, it does not allocate storage units to the parameters. It is allocated only when the function is called. After the function is called, it is immediately released. If a function is called multiple times, the storage unit of the parameter variable is allocated and released repeatedly. From the above analysis, we can see that static storage variables always exist, while dynamic storage variables sometimes disappear. We also name the lifetime of the variable because of its different storage methods. The lifetime indicates the time when the variable exists. The lifetime and scope describe the characteristics of variables from the two different perspectives of time and space. The two are both correlated and different. Which storage method does a variable belong to? It cannot be determined only from its scope. There should also be a clear description of the storage type.
In C, there are four types of storage for variables:
Auto auto variable
Register variable
Extern external variable
Static variables
Automatic variables and register variables are stored dynamically, while external variables and static variables are stored statically. After introducing the storage type of a variable, we can know that the description of a variable should not only describe its data type, but also describe its storage type. Therefore, the complete form of variable description should be: storage type description data type description variable name, variable name ...; For example:
Static int A, B; it indicates that a and B are static type variables.
Auto char C1, C2; indicates that c1 and c2 are automatic character variables.
Static int A [5] = {1, 2, 3, 4, 5}; indicates that A is a static integer array.
Extern int X, Y; it indicates that X and Y are external integer variables.
The following describes the above four Storage types:
1. The type specifier of the automatic variable is auto
This type of storage is the most widely used type in C language programs. According to the C language, all variables without storage type descriptions in the function are regarded as automatic variables, that is, automatic variables can save the specifier auto. Variables defined in the procedures in the previous chapter are automatic variables without the storage type specifiers. For example:
{Int I, J, K;
Char C;
......
} Is equivalent:
{Auto int I, J, K;
Auto char C;
......
}
Automatic variables have the following features:
1. The scope of the automatic variable is limited to the individual that defines the variable. The automatic variables defined in the function are valid only in the function. The automatic variables defined in the composite statement are only valid in the composite statement. For example:
Int KV (int A) {auto int X, Y; {auto char C;}/* c Scope */...... }/* Scope of A, X, and y */
2. Automatic variables are stored dynamically. They are allocated to a storage unit only when the function defining the variable is called to start its lifetime. Function call ends, the storage unit is released, and the lifetime ends. Therefore, the value of the automatic variable cannot be retained after the function call ends. The automatic variables defined in the composite statement cannot be used after exiting the composite statement. Otherwise, an error occurs. For example, the following program:
main() { auto int a,s,p; printf("/ninput a number:/n"); scanf("%d",&a); if(a>0){ s=a+a; p=a*a; } printf("s=%d p=%d/n",s,p); } { auto int a; printf("/ninput a number:/n"); scanf("%d",&a); if(a>0){ auto int s,p; s=a+a; p=a*a; } printf("s=%d p=%d/n",s,p); }
S and P are the automatic variables defined in the composite statement and can only be valid in the composite statement. The second row of the program outputs the values of S and P with the printf statement after exiting the compound statement, which will obviously cause errors.
3. Because the scope and lifetime of the automatic variable are limited to the individual defining it (within a function or compound statement), the variables of the same name can be used in different individuals without confusion. Even the automatic variables defined in the function can have the same name as the automatic variables defined in the compound statement within the function. Example 5.14 indicates this situation.
main() { auto int a,s=100,p=100; printf("/ninput a number:/n"); scanf("%d",&a); if(a>0) { auto int s,p; s=a+a; p=a*a; printf("s=%d p=%d/n",s,p); } printf("s=%d p=%d/n",s,p); }
This program defines the variable s twice in the main function and the compound statement, and P is the automatic variable. According to the C language, in a composite statement, the S and P defined in the composite statement take effect. Therefore, the s value should be a + A, and the P value is a *. After exiting the composite statement, P should be the S and P defined by main, and their values are given at initialization, all of which are 100. The output results show that two s and two P variables are the same, but they are two different variables.
4. Do not assign initialization values to automatic variables of the constructor type, such as arrays.
2. the type description of the external variable is extern.
The external variables have been introduced before. Here, we will explain several features of external variables:
1. external variables and global variables are two different definitions of the same class variables. Global variables are proposed from its scope, and external variables are proposed from its storage method, indicating its survival.
2. When a source program is composed of several source files, the external variables defined in the source file are also valid in other source files. For example, a source program consists of the source file f1.c and f2.c:
F1.c
Int A, B;/* external variable definition */Char C;/* external variable definition */main (){...... }
F2.c
Extern int A, B;/* external variable Description */extern char C;/* external variable Description */func (INT x, y ){...... }
The, B, and C variables must be used in both f1.c and f2.c files. Define A, B, and C as external variables in the f1.c file. In the f2.c file, use extern to describe the three variables as external variables, indicating that these variables have been defined in other files, and the types and names of these variables are described, the compilation system no longer allocates memory space for them. You can initialize and assign values to external variables of the construction type, such as arrays. If the initial values are not assigned, the system automatically defines their initial values as 0.
Iii. Static variables
The type description of static variables is static. Static variables are of course static storage, but the amount of static storage is not necessarily static variables. For example, although external variables are static storage, they are not necessarily static variables, A static external variable, or a static global variable, must be defined by static. For automatic variables, we have already introduced the dynamic storage method. However, static variables can also be defined as static automatic variables, or static local variables, to become a static storage method.
From this point of view, a variable can be re-described by static and its original storage method can be changed.
1. Static local variables
Add the static identifier before the local variable description to form a static local variable.
For example:
static int a,b; static float array[5]={1,2,3,4,5};
Static local variables are stored in static mode and have the following features:
(1) Static local variables are defined in the function, but they do not exist when called as automatic variables, and disappear when you exit the function. Static local variables always exist, that is, their lifetime is the entire source program.
(2) Although the lifetime of the static local variable is the entire source program, its scope is still the same as that of the automatic variable, that is, the variable can only be used within the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.
(3) allow initial values to be assigned to the static local volume of the constructor class. The array section describes how to initialize an array. If the initial value is not assigned, the system automatically assigns the value 0.
(4) If an initial value is not assigned to a static local variable of the basic type, the system automatically assigns the value 0. If the initial value is not assigned to the automatic variable, the value is not fixed. According to the characteristics of static local variables, it can be seen that it is a kind of lifetime for the entire source program. Although this function cannot be used after it is defined, it can continue to be used when the function is called again, and the value left after the previous call is saved. Therefore, when you call a function multiple times and require that the values of some variables be retained between calls, you can consider using static local variables. Although global variables can also achieve the above purpose, global variables sometimes cause unexpected side effects, so it is best to use local static variables.
[Example: 5.15]
Main () {int I; void F ();/* Function Description */for (I = 1; I <= 5; I ++) f (); /* function call */} void F ()/* function definition */{auto Int J = 0; ++ J; printf ("% d/N ", j );}
Function f is defined in the program, where variable J is an automatic variable and the initial value is 0. When F is called multiple times in main, J assigns the initial value 0, so each output value is 1. Change J to a static local variable. The program is as follows:
main() { int i; void f(); for (i=1;i<=5;i++) f(); } void f() { static int j=0; ++j; printf("%d/n",j); } void f() { static int j=0; ++j; printf("%d/n",j); }
Because J is a static variable, it can retain its value after each call and continue to be used in the next call. Therefore, the output value becomes a cumulative result. You can analyze the execution process on your own.
2. Static global variables
The description of global variables (external variables) is preceded by static to form a static global variable. Global variables are static storage, and static global variables are also static storage. The two are not different in storage methods. The difference between the two lies in that the scope of non-static global variables is the entire source program. When a source program is composed of multiple source files, non-static global variables are valid in each source file. The static global variable limits its scope, that is, it is valid only in the source file defining the variable, and cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file. Therefore, errors in other source files can be avoided. From the above analysis, we can see that after a local variable is changed to a static variable, its storage mode is changed, that is, its survival time is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use. Therefore, the description of static plays different roles in different places. Attention should be paid.
Iv. register variables
All the above variables are stored in the memory. Therefore, when a variable is frequently read/written, it must be accessed repeatedly to consume a large amount of access time. Therefore, the C language provides another variable, register variable. These variables are stored in the CPU registers. When used, they do not need to access the memory, but are directly read and written from the registers, which improves efficiency. The register variable description is register. Variable control variables with a large number of cycles and variables used repeatedly in the loop body can be defined as register variables.
Calculate the sum of all numbers from 1 to 200.
main() { register i,s=0; for(i=1;i<=200;i++) s=s+i; printf("s=%d/n",s); }
This program loops 200 times, and I and S are frequently used. Therefore, it can be defined as a register variable. The register variables should also be described as follows:
1. Only Local Automatic variables and formal parameters can be defined as register variables. Because register variables are dynamically stored. The amount of data that requires static storage cannot be defined as register variables.
2. In the C language used on Turbo C, ms c and other computers, the register variable is actually treated as an automatic variable. Therefore, the speed cannot be improved. In the program, register variables are only allowed to be consistent with standard C. 3. Even if the machine can actually use register variables, the number of registers in the CPU is limited, so the number of register variables is limited.
C variable type and scope