C ++ (4): variables and variables
Local variable
Variables defined in a function are internal variables, which are valid only within the scope of the function. That is to say, they can only be used in this function, and cannot be used outside of this function. Similarly, the variables defined in composite statements are valid only within the scope of this composite statement. This is called a local variable ).
Some local variables are described as follows:
1) the variables (m, n) defined in the main function are only valid in the main function and are not valid in the entire file or program because they are defined in the main function. The main function cannot use the variables defined in other functions.
2) variables with the same name can be used in different functions. They represent different objects and do not interfere with each other. For example, variables B and c are defined in the f1 function. If the f2 function also defines the variables B and c, they occupy different units in the memory and will not be confused.
3) You can define variables in a compound statement in a function. These variables are only valid in this compound statement. This compound statement is also called a program or program block.
4) The form parameter is also a local variable. For example, the form parameter a in the f1 function is only valid in the f1 function. Other functions cannot be called.
5) The parameter name that appears in the function declaration is only included in the brackets of the row. In fact, the compilation system ignores the variable names in the function declaration, even if they are not allocated storage units when calling the function. For example:
Int max (int a, int B); // function declaration contains a, bint max (int x, int y) // function definition, the parameters are x, y {cout <x <y <endl; // valid. x and y are valid cout <a <B <endl; // invalid. a and B are invalid in the function body}
A and B in the max function body are not defined during compilation. As described earlier, the program compilation unit is the source program file. A source file can contain one or more functions. Variables defined in a function are local variables, while variables defined outside the function are external variables, known as global variables ). The valid range of a global variable is from the position of the defined variable to the end of the source file.
You can use both local variables and valid global variables in a function.
Some global variables are described as follows:
1) global variables are used to increase the data connection channels between functions.
2) We recommend that you do not use global variables when necessary, because:
- Global variables occupy storage units during all program execution, rather than opening up units only when needed.
- This reduces the versatility of the function because it is affected by external variables when executing the function. If you move a function to another file, you also need to move the related external variables and their values together. However, if the external variable has the same name as the variable in other files, the problem may occur, reducing the program's reliability and versatility. In program design, the module requires strong cohesion and weak coupling with other modules. That is, the module functions should be single (do not put many unrelated functions into one module), and the interaction with other modules should be minimized, however, using global variables does not conform to this principle.
- Generally, functions in the program must be made into a closed body. In addition to being connected to the outside world through the "real parameter-form parameter" channel, there are no other channels. Such a program is highly portable and readable.
- Using too many global variables Reduces Program clarity. Global variable values may be changed during function execution, and errors may occur in the program. Therefore, you must restrict the use of global variables.
3) if the global variable has the same name as the local variable in the same source file, the global variable is blocked within the scope of the local variable, that is, it does not work.
The effective scope of a variable is called the scope of the variable ). To sum up, variables have four different scopes, file scope, function scope, and block scope) and function prototype scope ). The file scope is global, and the other three are local.
In addition to variables, any entity represented by identifiers has a scope, similar to the scope of variables.
Storage Class of C ++ variables (dynamic storage, static storage, automatic variables, register variables, and external variables)
Dynamic and Static storage methods we have learned about the scope of variables. The scope is analyzed from the perspective of space, including global variables and local variables.
Another property of a variable is storage duration ). Storage period refers to the period when a variable exists in the memory. This is analyzed from the perspective of the time when the variable value exists. The storage period can be divided into static storage duration and dynamic storage duration ). This is determined by the static and dynamic storage methods of variables.
Static storage means that the system allocates a fixed storage space for variables during the program running. The dynamic storage method dynamically allocates storage space to variables during the program running.
Let's take a look at the storage space in the memory for users. This bucket can be divided into three parts:
- Procedure Area
- Static storage Zone
- Dynamic Storage Zone
Fig 4.1
Data is stored in the static and dynamic storage areas. Global variables are all stored in the static storage area. When the program starts to execute, global variables are allocated with storage units. After the program is executed, the space is released. They occupy fixed storage units during program execution, rather than dynamically allocating and releasing them.
Store the following data in the dynamic storage area:
- Function Form parameters. When you call a function, allocate storage space to the parameters.
- Automatic variables in the function (local variables without static Declaration are described later ).
- Field Protection and return address during function calling.
For the above data, dynamic storage space is allocated at the beginning of the function call, and the space is released at the end of the function. During program execution, the allocation and release are dynamic. If the same function is called twice in a program, the allocation and release are performed twice, the bucket addresses allocated to the local variables in this function may be different twice.
If a program contains several functions, the storage period of local variables in each function is not equal to the execution period of the entire program. It is only part of the execution cycle of the program. Based on function calls, the system dynamically allocates and releases buckets for local variables.
In C ++, variables include data type attributes and storage class attributes. Storage Class refers to the method for storing data in memory. Storage methods can be classified into static storage and dynamic storage. There are four types: auto, static, register, and extern ). According to the storage class of the variable, you can know the scope and storage period of the variable.
If the local variables in the automatic variable function are declared without the keyword static, the compilation system dynamically allocates storage space for them. The form parameters of the function and the variables defined in the function (including the variables defined in the composite statement) belong to this class. When this function is called, The system allocates storage space to the variables defined in the parameters and functions, and the data is stored in the dynamic storage area. The space is automatically released at the end of the function call. If the variable is defined in the composite statement, the storage space is allocated when the variable is defined, and the space is automatically released when the composite statement ends. Therefore, such local variables are called automatic variables ). Auto variables use the keyword auto for the storage class declaration. For example:
Int f (int a) // defines the f function. a is the form parameter.
{
Auto int B, c = 3; // defines the automatic variables in which B and c are integers.
}
The order of storage class auto and Data Type int is arbitrary. The keyword auto can be omitted. If auto is not written, the system sets it as the automatic storage class by default, which belongs to the dynamic storage mode. Most variables in the program are automatic variables. In the example described in the previous chapter of this tutorial, all variables defined in the function are not declared as auto. In fact, they are all specified as auto variables by default. In the function body, the following two statements share the same purpose:
Auto int B, c = 3;
Int B, c = 3;
Static declaration of static local variables sometimes requires that the value of local variables in the function do not disappear after the function call ends and keep the original value, that is, the storage units occupied by the function are not released. During the next call of the function, this variable retains the value at the end of the callback function call. In this case, you should specify this local variable as a static local variable ).
[Example 4.1] Static local variable value.
# Include <iostream> using namespace std; int f (int a) // defines the f function. a is the form parameter {auto int B = 0; // define B as the automatic variable static int c = 3; // define c as the static local variable B = B + 1; c = c + 1; return a + B + c;} int main () {int a = 2, I; for (I = 0; I <3; I ++) cout <f (a) <"; cout <endl; return 0 ;}
The running result is:
7 8 9
When the f function is called three times, the values of B and c are shown in table 4.1.
Table 4.1 values of automatic and static local variables when a function is called
Number of calls |
Initial Value During call |
Value at the end of the call |
Automatic Variable B |
Static local variable c |
B |
C |
A + B + c |
1st times |
0 |
3 |
1 |
4 |
7 |
2nd times |
0 |
4 |
1 |
5 |
8 |
3rd Times |
0 |
5 |
1 |
6 |
9 |
Fig 4.2
Description of static local variables:
- Static local variables are allocated to storage units in the static storage area. The program is not released during the entire running period. Automatic variables (that is, dynamic local variables) belong to the dynamic storage class. They are stored in the dynamic storage space (rather than the static storage space) and are released after function calls.
- Assigning an initial value to a static local variable is performed at compilation, that is, only the initial value is assigned once and it has an initial value when the program is running. In the future, the initial values will not be re-assigned for each function call, but the values at the end of the last function call will be retained. However, assigning an initial value for an automatic variable is not performed during compilation, but during function calling. Every time the distinct function is called, the initial value is re-assigned, which is equivalent to executing a value assignment statement.
- If initial values are not assigned when defining local variables, the initial values 0 (For numeric variables) or null characters (For numeric variables) are automatically assigned during compilation ). For an automatic variable, if the initial value is not assigned, its value is an uncertain value. This is because the storage unit has been released after each function call, and the storage unit is re-allocated in the next call. The value in the allocated unit is uncertain.
- Although static local variables still exist after the function call, other functions cannot reference them, that is, they are "invisible" in other functions.
Under what circumstances do local static variables need to be used?
1) the value at the end of the last call of the function needs to be retained. For example, you can use the method in the following example to calculate n !.
[Example 4.2] Output 1 ~ The factorial value of 5 (that is, 1 !, 2 !, 3 !, 4 !, 5 !).
# Include <iostream> using namespace std; int fac (int); // function declaration int main () {int I; for (I = 1; I <= 5; I ++) cout <I <"! = "<Fac (I) <endl; return 0;} int fac (int n) {static int f = 1; // f is a static local variable, at the end of the function, f is not released. f = f * n; // multiply the value of f by n return f ;}
The running result is
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
Each time you call fac (I), an I is output and the I is retained! To multiply (I + 1) next time ).
2) After initialization, if the variable is referenced only without changing its value, it is convenient to use static local variables to avoid re-assigning values for each call. However, it should be seen that static storage occupies more memory and reduces the readability of the program. When there are many calls, it is often difficult to figure out the current value of static local variables. Therefore, do not use static local variables unless necessary.
Declare a register variable with register. Generally, the value of the variable is stored in the memory. When the value of a variable is used in the program, the controller sends the value of this variable in the memory to the timer in the CPU. After calculation by the memory, if you need to store the data, the data is sent from the memory to store. 4.3.
Fig 4.3
To improve execution efficiency, C ++ allows you to put the value of local variables in the registers of the CPU. When necessary, you can directly retrieve the values from the registers for calculation without having to access them in the memory. This type of variable is called a register variable and is declared using the keyword register. For example, you can rewrite the fac function in example 4.3 as follows:
Int fac (int n) {register int I, f = 1; // defines that I and f are register variables for (I = 1; I <= n; I ++) f = f * I; return f ;}
Defining f and I is a local variable stored in the register. If the value of n is large, it can save a lot of execution time.
Defining register variables in a program is only necessary (rather than mandatory) for the compilation system. Today's optimized compilation system can identify frequently used variables and automatically place these variables in registers.
The global variable (external variable) declared with extern is defined outside the function. Its scope is from the definition of the variable to the end of the program file. In this scope, global variables can be referenced by each function in this file. Global variables are allocated to the static storage area during compilation.
Sometimes you need to use extern to declare global variables to extend the scope of global variables.
1) Declare global variables in a file
If the external variable is not defined at the beginning of the file, its effective scope is limited to the end of the file at the definition. If the function before the definition point wants to reference this global variable, you should use the keyword extern to declare this variable before the reference, this variable is a global variable that will be defined below. With this declaration, you can legally reference the global variable from the declaration. This declaration is called the Early reference declaration.
[Example 4.4] Use extern to declare external variables in advance to extend the scope in the program file.
# Include <iostream> using namespace std; int max (int, int); // function declaration void main () {extern int a, B; // for global variable, B For early reference declaration cout <max (a, B) <endl ;}int a = 15, B =-7; // defines the global variable, bint max (int x, int y) {int z; z = x> y? X: y; return z ;}
The running result is as follows:
15
The global variables a and B are defined after main. However, because the position defined by the global variables is after the main function, if there is no program line 5th, global variables a and B cannot be referenced in the main function. Now we use extern in row 2nd of the main function to declare a and B in advance, indicating that a and B are the variables that will be defined later. In this way, the global variables a and B can be used legally in the main function. If no extern declaration is made, an error occurs during compilation. The system determines that a and B are not defined. Generally, the definition of global variables is placed before all the functions that reference them. This avoids adding an extern declaration to the function.
2) Declare external variables in Multi-file programs
If a program contains two files, the same external variable num must be used in both files. The two files cannot define an external variable num respectively. The correct method is to define the external variable num in any file, and use extern in another file to declare the external variable num. That is
Extern int num;
The compilation system knows that num is an external variable defined elsewhere. It first finds whether there is an external variable num in this file, extend its scope to the beginning of the line (as described in the preceding section). If there are no other variables in this file, find the external variable num from other files during program connection, if so, extend the scope of the external variable num defined in another file to this file. In this file, the external variable num can be legally referenced.
Analysis example:
Filel. cpp
Extern int a, B;
Int main ()
{
Cout <a <"," <B <end !;
Return 0;
}
File2.cpp
Int as3, B = 4;
Bytes
In the source program file ffle2.cpp, the integer variables a and B are defined, and the initial values are obtained. In filel. cpp, use extern to declare the external variables a and B. The value is not writable. After compiling and connecting to a program, the scopes of a and B in file2.cpp are extended to the file2.cpp file. Therefore, the cout statements in the main function output the values of a and B to 3 and 4.
Although using extern to extend the scope of global variables can bring convenience to program design, it should be very careful because the value of global variables may be changed when a function in a file is executed, this will affect the function execution results in another file.
Static declaration of static external variables sometimes requires some external variables to be referenced only by this file in the program design, but not by other files. In this case, you can add a static declaration when defining external variables. For example:
File1.cpp
Static int a = 3;
Int main ()
{
Bytes
}
File2.cpp
Extern int;
Int fun (int n)
{
Bytes
A = a * n;
Bytes
}
In filel. cpp defines a global variable a, but it is declared using static, so it can only be used in this file, although the cpp file uses "extern int ;", however, filel is still unavailable in the file2.cpp file. the global variable a in cpp.
The external variables (global variables) added with the static Declaration can only be used in this file are called static external variables. This provides convenience for the modularization and universality of the program. If you already know that other files do not need to reference the global variables of this file, you can add static variables to the global variables in this file to become static external variables to avoid misuse of other files.
It should be noted that the static storage method (stored in the static storage area) should not be used for external variables declared using static statements ), dynamic Storage (stored in the dynamic storage area) is not static ). In fact, both forms of external variables use static storage, but the scope is different, and the memory is allocated during compilation.
Input four variables in C language, sort them in a descending order, and output the commands to save your urgent needs.
# Include <stdio. h> int main ()
{Int a, B, c, d, t;
Printf ("please enter 4 integer numbers: \ n ");
Scanf ("% d", & a, & B, & c, & d );
If (a <B) {t = a; a = B; B = t ;}; if (a <c) {t = a; a = c; c = t ;};
If (a <d) {t = a; a = d; d = t ;};
If (B <c) {t = B; B = c; c = t ;};
If (B <d) {t = d; d = B; B = t ;};
If (c <d) {t = c; c = d; d = t ;};
Printf ("the four numbers are sorted in ascending order: % d \ n", a, B, c, d); return 0;
}
Write a c program and define four character variables c1, c2, c3, and c4. Use the getchar () function to input four letters and output the most
# Include <stdio. h>
Void main ()
{
Char c1, c2, c3, c4, t;
C1 = getchar ();
C2 = getchar ();
C3 = getchar ();
C4 = getchar ();
If (c1> c2)
{T = c1; c1 = c2; c2 = t ;}
If (c1> c3)
{T = c1; c1 = c3; c3 = t ;}
If (c1> c4)
{T = c1; c1 = c4; c4 = t ;}
If (c2> c3)
{T = c2; c2 = c3; c3 = t ;}
If (c2> c4)
{T = c2; c2 = c4; c4 = t ;}
If (c3> c4)
{T = c3; c3 = c4; c4 = t ;}
Printf ("max = % c, min = % c \ n", c4, c1 );
}