From

xiaoxiao2021-03-06  116

Word Source VC World - C language classroom

Self-archiving, also dedicated to the same Delphi programmer as me

function

Overview

In the first chapter, the C source program is composed of a function. Although there is only one main function main () in the procedure of each chapter, the utility is often composed of multiple functions. The function is the basic module of the C source program, and the specific function is implemented by the call to the function module. The function in the C language is equivalent to the subroutine of other advanced languages. The C language not only provides an extremely rich library function (such as Turbo C, MS C provides more than 300 library functions), but also allows users to establish their own defined functions. Users can make their algorithms into a relatively independent function module, then use the function with the call.

It can be said that all of the works of the C program is done by a wide variety of functions, so the C language is also called a functional language. The C language is easy to implement structured programming due to the functional module structure. Make the hierarchy of the program clear, easy to write, read, and debug.

The function can be classified from different angles in the C language.

1. From the perspective of the function definition, the function can be divided into two types of library functions and user-defined functions.

(1) The library function is provided by the C system, and the user does not have to define, nor does it need to be described in the program, just call the header file that contains the function prototype before the program can be called directly. In the first chapter, it is repeatedly used to use the printf, scanf, getcha, putcha, gets, puts, and strcat, etc.

(2) User-defined functions are written by the user as needed. For user-defined functions, it is necessary to define a function itself in the program, but also in the Motor Module, the modular function must be described, and then it can be used.

2. The function of the C language has both functions and processes in other languages. From this perspective, the function can be divided into two types of return value and non-return value function.

(1) After returning value function This type of function is called executed, it will return an execution result to the caller, referred to as a function return value. If the mathematical function is such a function. This function that is defined by the user must return a function value must be explicitly returned in the function definition and function description.

(2) None return value function This type of function is used to complete a specific processing task, and do not return a function value to the caller after execution. Such functions are similar to the process of other languages. Since the function does not have to return a value, the user can specify its return to "empty type" when defining such a function, and the empty type is "Void".

3. From the perspective of data transfer from the main adjustment function and the modulated function, it can be divided into two kinds of no reference functions and between the number of functions.

(1) No parameters in the function function definition, function description and function calls are not used. Parameter transfer is not performed between the main adjustment function and the modulated function. Such functions are usually used to complete a set of specified features, which can return or do not return a function value.

(2) The ginseng function is also known as a band function. There is a parameter when the function definition and function description are called, called a formal parameter (referred to as a meticulous). Parameters must also be given when the function call is called, called the actual parameter (referred to as inform). When performing a function call, the main adjustment will transmit the value of the value of the argument to the invitiveing ​​function.

4. The C language provides an extremely rich library function, which can be classified by the functional angle. (1) Character type classification function is used to classify the character: letters, numbers, control characters, separators, uppercase letters, etc. (2) The conversion function is used for the conversion of characters or strings; converts between character quantities and various digital quantities (integer, real-purpose, etc.); transitions between large and lowercases. (3) Directory path functions are used for file directory and path operation. (4) The diagnostic function is used for internal error detection. (5) Graphics functions are used for screen management and various graphics functions. (6) The input and output function is used to complete the input and output function. (7) The interface function is used to interface with DOS, BIOS, and hardware. (8) String function is used for string operation and processing. (9) The memory management function is used for memory management. (10) Mathematical functions are used for mathematical functions. (11) Date and time functions are used for dates, time conversion operations. (12) Process control function is used for process management and control. (13) Other functions are used in other functions. The above various types of functions are not only a number, but some need hardware knowledge will be used, so they need a longer learning process. You should first grasp some of the most basic, most common functions, and then gradually deeply. Due to the space relationship, this book only introduces a few partial library functions, and the rest of the readers can check the relevant manual as needed. It should also be noted that in the C language, all function definitions, including the main function main, is parallel. That is to say, in a function of a function, another function cannot be defined, ie the definition cannot be nested. However, the function is allowed to call each other and the nested call is allowed. It is used to call the caller as the main adjustment function. The function can also call yourself, called recursive calls. The main function is the main function, which can call other functions without allowing to be called by other functions. Therefore, the execution of the C program always begins with the main function, and then returns to the main function after the call to other functions, and finally the entire program is ended by the main function. A C source must have, and only one main function main. General form of function definition

1. General Form Type Type Descript Function Name () {Type Description Statement} The type of function name is a function header. Type Descript specifies the type of this function, the type of function is actually the type of function returns. This type of specifier is the same as the various instructions described in Chapter 2. The function name is an identifier defined by the user, and there is an empty bracket after the function name, with no parameters, but parentheses are not less. The content in {} is called a function body. There is also a type of description in the function body, which is an illustration of the type of variable used inside the function. In many cases, there is no need to have a return value without the number of refactors, and the function type can be written as a Void. We can change to a function definition: void Hello () {Printf ("Hello, World / N");} Here, only Main change is used as a function name, the rest remain. The Hello function is a non-gatcher that outputs a Hello World string when called by other functions.

2. General Form Type Type Description Function Name (Form Parameter Table) Type Parameter Type Description {Type Description Statement} There are more than two contents than no references, one is the formal parameter table, the second is Form parameter type description. The parameters given in the Distake are called the formal parameters, which can be variables of various types, with comma intervals between parameters. When a function call is performed, the Motor is given the actual value of these form parameters. Solden Side is variable, of course, must be given to the type. For example, define a function, for the large number of two numbers, can be written as: int MAX (A, b) INT A, B; {IF (A> B) Return A; Else Return B;} first The row indicates that the MAX function is an integer function that the function value returned is an integer. Conversion is A, B. The second lines illustrates A, B is an integer amount. The specific value of A, B is transmitted by the main adjustment function. In the function body in {}, the deoxy is not used to use other variables, so there is only a statement without a variable type description. This definition method is called "traditional format". This format is not easy to compile the system check, which will cause some very thin and difficult to track errors. ANSI C's new standard consolidates the type of parameter into the medial, called "modern format". For example, the MAX function can be defined as: int Max (int A, int b) {if (a> b) Return A; ELSE RETURN B;} Modern format In function definition and function description (later will be introduced), give Form parameters and their types, which are easy to check them when compiling, ensuring the consistency of function descriptions and definitions. This modern format is used in Example 1.3. The return statement in the MAX function is returned to the main tuning function for the value of A (or B) as a function. There should be at least one Return statement in the return value function. In the C program, the definition of a function can be placed anywhere, and can be placed after the main function main can also be placed. For example, an MAX function is defined in Example 1.3, and its location can then put it before main. The modified program is as follows. INT MAX (INT A, INT B) RETURN A; Else Return B;} void main () {int MAX (int A, int b); int X, y, z; printf ("Input) Two numbers: / n "); scanf ("% D% D ", & x, & y); z = max (x, y); printf (" maxmum =% d ", z);} Now we can define from the function , Function descriptions and function calls to analyze the entire program, further understand various features of the function. The first line to the 5th behavioral MAX function is defined. After entering the main function, because the MAX function is prepared, the MAX function will be described (the program 8). Function definitions and function description are not one thing, but also discuss it later. It can be seen that the function description is the same as the function header in the function definition, but at the end to add a division. The 12th behavior of the program calls the MAX function and transmits the value of X, Y to Max, B. The result of the MAX function (A or B) will return to the variable z. Finally, the value of z is output by the main function. The general form of function call has been said, in the program, by performing a function of the function, which is similar to the subroutine calls in other languages. In the C language, the general form of function call is:

Function Name (actual parameter table) No actual parameter table when invoking contactless function. The parameters in the actual parameter table can be constant, variables, or other constructive type data and expressions. The comma is separated between the comma. 'Next Of Page In C Language, you can call functions in the following ways: 1. Function Expression Function The expression in the expression is in the expression, with a function return value to participate in the expression. This method requires a function of returning. For example: z = max (x, y) is an assignment expression that imparts the return value of the MAX to the variable z. 'Next of Page2. The general form of function statement function calls plus the semicolon constituting the function statement. For example: Printf ("% d", a); scanf ("% d", & b); all call functions in the way of function statements. 3. Function The actual parameters appear as another function call. This is to transmit the return value of the function as the argument, so that the function must be returned. For example: Printf ("% D", max (x, y)); ie, the return value of the MAX call is used as the first parameters of the Printf function. One problem should be noted in the function call is the problem of evaluating the order. The so-called quotation order refers to the use of various amounts from left to right in the real parameter table, or is used to left. In this regard, the provisions of each system are not necessarily the same. When introducing the Printf function in Section 3.1.3, it has been mentioned here. Example 5.2 program. Void main () {INT i = 8; Printf ("% D / N% D / N% D / N% D / N", i, - i, i , i -);} If you follow The order of right to the left is evaluated. Example 5.2 The operation result should be: 8778, such as i, - i, i , i --- from left to right, the result should be: 9889 should pay special, whether it is from left To the right value, or from right to left, the output order is constant, that is, the output order is always the same as the order in the field in the field. Since Turbo C is currently from right to left, the result is 8, 7, 7, 8. If the above problem is not understood, I will understand it. The value of the function of the function. 1. The value of the function is described. In this section, further introduce the characteristics of the caminance, the arguments, and the relationship between the two. Conversion in the function definition, can be used in the entire function body, and cannot be used by leaving the function. In the main debut function, the real parameter variable cannot be used after entering the modulated function. The function of the meticulum and the argument is data transfer. When a function call is invoked, the main adjustment function transmits the value of the actor to the invisible function to implement the data transfer of the main adjustment function. The function of the function has the following characteristics: 1. The variable variable variable is allocated to allocate the memory unit when the call is called, and the assigned memory unit is released immediately at the end of the call. Therefore, the shape is only valid inside the function. The function call ends that after returning the main adjustment function, it cannot be used again.

2. The arguments can be constants, variables, expressions, functions, etc., regardless of the amount of the type of arguments, they must have a determined value when performing a function call to deliver these values. Therefore, it should be pre-assigned, input, etc., the input should be used to obtain the determined value.

3. In the number, the type, the type, the type, the order should be strict, otherwise the "type mismatch" error will occur.

4. Data transfer that occurs in function call is one-way. That is, only the value of the arguments can be transmitted, and the value of the parameter cannot be reversed to the argument. Therefore, during the function call, the value of the parameter changes, and the value in the inactors will not change. Example 5.3 can illustrate this problem. Void main () {Int n; Printf ("Input Number / N"); Scanf ("% D", & N); S (N); Printf ("n =% D / N", N);} int S (int N) {INT i; for (i = N-1; I> = 1; i -) n = n i; printf ("n =% d / n", n);} defined in this program A function S, the function of this function is the value of σni = 1i. Enter the n value in the main function, and act as the argument, the shape parameter n to the S function is transmitted during the call (note that the identifier of this example is N, but this is two different The amount, the respective scope of action). The n value is output with a PrintF statement in the main function, which is the value of the solid parametric N. The n value is output with the PrintF statement in the function S, which is the N value 0 obtained by the final acquired. From the operation, the input n value is 100. That is, the value of the solid parameters is 100. When this value is transmitted to the function S, the initial value of the meticulin N is also 100. During the execution function, the value of the metallin N is 5050. After returning the main function, the value of the output solids N is still 100. It can be seen that the value of the argument is not changed. Second, the value of the function

The value of the function is that the function is called after being called, and the value taken by the program segment in the function body is executed and returned to the main adjustment function. If the sine function is called, the maximum number of MAX functions of the Call Example 5.1 is called. There are some other descriptions for the value of the function (or the function return value):

1. The value of the function can only return the main adjustment function via the return statement. The general form of the RETURN statement is: Return expression; or: return (expression); the functionality of this statement is the value of the expression, and returns to the main tuning function. There are multiple return statements to be permitted in the function, but only one Return statement can be executed each time the call is executed, so it can only return a function value.

2. The type of function value and the type of functions in the function definition should be consistent. If the two are inconsistent, the type conversion is automatically performed by the type of function.

3. If the function value is integer, you can save the type description when the function is defined.

4. Do not return a function of the function value, can be explicitly defined as "empty type", the type specifier is "void". As in Example 5.3, the function S does not return a function value to the main function, so it can be defined as: Void S (INT N) {...}

Once the function is defined as an empty type, the function value of the modulated function cannot be used in the main adjustment function. For example, after defining S is an empty type, write the following statement SUM = S (N) in the main function; it is incorrect. In order to make the program have good readability and reduce errors, all functions that do not require return values ​​should be defined as empty types. Function Description Cables to the modulated function before calling a function in the main adjustment function, which is the same as that of the variable before using the variable. The purpose of the modulated function in the main adjustment function is to enable the compilation system to know the type of the value returned to the value of the value to be processed accordingly in this type of return value in this type in the main adjustment. There are also two formats for the modular function, one is a traditional format, which is generally format: Type spectrum is being adjusted (); this format only gives the type of function return value, the number name and one Empty bracket.

This format is not easy to check in the compilation system due to any parameter information in parentheses, so it is easy to perform errors in the compilation system. The other is modern format, its general form is: Type spectrum is being adjusted (type ginseng, type ginseng ...); or: Type spectrum is being adjusted (type, type ...); modern format The type and shape reference nominal of the ginseng is given in parentheses, or only the visible ginseng type. This makes it easy to compile the system for error to prevent possible errors. Example 5.1 Instructions for MAX functions in the MAIN function, if you can use the traditional format: int max (); written in modern format: int Max (int A, int b); or write as: int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int ); C language also specifies that the function description of the modulated function in the main adjustment function can be omitted in the following cases. 1. If the return value of the modulated function is an integer or character type, it may not be described directly, and directly call. At this time, the system will automatically return the value of the modulated function to the value. The function S is not described in the main function of Example 5.3, which is directly called. 2. When the function definition of the modulated function appears before the Motor function, the modular function may not be called directly to the modified function. For example, in Example 5.1, the definition of the function Max is placed before the main function, so it can save the function of the MAX function in the main function, Int Max (Int A, INT B).

3. As before all function definitions, the type of each function is pre-described in the function, and in the next main adjustment function, the modulated function can no longer be described. For example: char STR (INT A); float b); main () {...} char str (int a) {...} float f (float b) {...} in the first, two lines The STR function and the F function pre-explained. Therefore, there is no need to be called directly in each function to make an explanation of the STR and F functions.

4. The call to the library function does not need to be explained, but the header file of the function must be included in the front of the source file with the incrude command. Array as a function parameter array can be used as a parameter of a function, and data transmission is performed. The array has two forms for function parameters, one is to use array elements (subscript variables) as an argument; the other is to use the array name as a function of the function of the function. First, the array element make functions real parameter group elements are the subscript variable, which is not different from ordinary variables. Therefore, it is identical as a function as a function as the normal variable is exactly the same. When the function is called, the value of the value of the array element as the argument is transmitted, and the one-way value is transmitted. Example 5.4 illustrates this situation. [Example 5.4] A value of each element in an integer array is discriminated, and the value is output if it is more than 0, and the 0 value is output if it is less than 0. Programming as follows: Void NZP (INT V) PRINTF ("% D", V); ElsePrintf ("% D", 0);} main () {Int a [5], i; printf ("INPUT 5 NUMBERS / N"); for (i = 0; i <5; i ) {scanf ("% d", & a [i]); NZP (a [i]);}} void NZP (int v) {...} main () {int a [5], i; printf ("INPUT 5 NUMBERS / N"); for (i = 0; i <5; i ) {scanf ("% d", & a [I]); NZP (a [i]);}} This program first defines a non-return value function NZP and indicates that its shape V is integer variable. The corresponding result is output according to the V value in the function body. In the main function, enter an array of each element in the main function. Each input is used to use the NZP function with this element, ie the value of the value of the A [i] is used to use the NZP function. Second, the array name as a function parameter

Use the number of group names function parameters and use of array elements to participate in several points: 1. When using array elements, as long as the array type and function's type variable variable, then the type of array element as a subscript variable Also consistent with the type of the functional parameters. Therefore, the metastin of the function is not required is also a subscript variable. In other words, the processing of the array elements is treated in normal variables. When using an array name to function parameters, the arranging arguments corresponding to the requirements must be the same as the same number, and must have a clear array description. An error occurs when the meticulous and the inquiry are inconsistent.

2. When the normal variable or subscript variable is functional parameters, the denominating variables and the real parameters are two different memory cells allocated by the compilation system. The value that occurs when the function call is transmitted to the value of the value of the real parameters. When using an array name to function parameters, it is not a value of the value, ie not the value of each element of the real parameter group, is imparted by each element of the array group. Because the actual parallel parameter group does not exist, the compilation system is not allocating memory. So, how is the transfer of data? In Chapter 4, we have introduced that the array name is the first address of the array. Therefore, the transfer only when the array name is functional parameters, that is, the first address of the real parameter group is given the name parameter group name. After the first address is obtained, it is equivalent to a real array. In fact, the shape parameter group and the real parameter group are the same array, together with a memory space. Figure 5.1 illustrates this situation. Set A is a real parameter, type is integer. a a memory area that has the address of the address of 2000. b is a group name name. When a function call occurs, the address transfer is performed, and the first address of the real parameter group A is transmitted to the formation parameter group name B, so B also acquires the address 2000. Thus, a, b two arrays share a continuous memory unit with a first address of 2000. It can also be seen from the figure that the same elements as those subscribed by the A and B are actually the same two memory cells (all elements of the integer array account for two bytes). For example, A [0] and B [0] occupy 2000 and 2001 units, of course, A [0] is equal to B [0]. The type of push is A [I] equal to B [I]. [Example 5.5] A group A stored a 5-course score of 5 courses, and seeking average score. FLOAT AVER (FLOAT A [5]) {INT I; FLOAT AV, S = a [0]; for (i = 1; i <5; i ) s = s a [i]; av = s / 5; Return av;} void main () {float sco [5], av; int i; printf ("/ ninput 5 score: / n"); for (i = 0; i <5; i ) scanf ("% f ", & sco [i]); av = AVER (SCO); Printf (" Average Score IS% 5.2F ​​", AV);} Float Aver (Float AVER (Float A") {...} void main () {... For (i = 0; i <5; i ) scanf ("% f", & sco [i]); av = aVER (SCO); ...} This program first defines a realistic function AVER, there is a ginseng For the real array A, the length is 5. In the function aVER, each element value is added to the average value, and return to the main function. The input of the array SCO is first completed in the main function main, and then the AVER function is used as a real parameter, the function returns the value to send AV, and finally outputs the AV value. As can be seen from the operation, the program implements the required functionality

3. The previously discussed, when the variable is functional parameters, the value transmitted is unidirectional. That is, it can only be treated from the immersion direction, and the solid group cannot be passed from the shape. The initial value of the meticulin is the same, and the value of the parametric is changed, and the first value of the two is different. Example 5.3 confirmed this conclusion. When using an array name, the situation is different. Due to the actual number of parameter groups, the active parameter group varies. Of course, this situation cannot be understood as a "two-way" value transmission. However, from the actual situation, the value of the real parameter group will vary depending on the change in the value of the array. To illustrate this, Change Example 5.4 is in the form of Example 5.6. [Example 5.6] The topic is 5.4 cases. Use the number of group name made functions parameters. Void NZP (INT A [5]) {INT I; Printf ("/ NVALUES OF ARRAY a Are: / N"); for (i = 0; I <5; I ) {IF (A [i] <0) A [i] = 0; Printf ("% D", A [I]);}} main () {INT B [5], I; Printf ("/ Ninput 5 Numbers: / N"); for (i = 0; I <5; I ) Scanf ("% D", & B [I]); Printf ("INITIAL VALUES OF ARRAY B Are: / N); for (i = 0; I <5; i ) Printf ("% D", B [I]); NZP (b); Printf ("/ NLAST VALUES OF ARRAY B Are: / N"); for (i = 0; I <5; i ) Printf ("% D ", B [I]);} Void NZP (INT A [5]) {...} main () {Int B [5], i; ... NZP (b); ...} The function NZP in this program The meticulum is an integer group A, and the length is 5. In the main function, the real parameter group B is also integrated, and the length is also 5. First enter the value of array b in the main function, then output the initial value of array B. Then use the array name B to modify the NZP function. In NZP, the negative value unit is set as required, and the value of the shape parameter set A is output. After returning the main function, output the value of the array b again. As can be seen from the operation results, the initial value and final value of the array B are different, the final values ​​and array A of the array B are the same. This means that the reference is the same as the same array, and their values ​​are changed at the same time. Note the following points when using an array name as a function parameter: a. The type of array and real parameter array must be consistent, otherwise an error will cause errors. b. The length of the shape parameter group and the real parameter group may be different, because when the call is called, only the first address is transmitted without checking the length of the argument group. When the length of the shape parameter group is inconsistent with the real parameter group, although the syntax error (compiled can pass), the program execution result will not be in good agreement, which should be noted.

If you modified as follows: Void NZP (INT A [8]) {INT I; Printf ("/ NVALUES OF ARRAY AARE: / N"); for (i = 0; i <8; i ) {IF (A [i] <0) a [i] = 0; Printf ("% d", a [i]);}} main () {INT B [5], i; printf ("/ ninput 5 numbers: / n "); for (i = 0; i <5; i ) scanf ("% d ", & b [i]); Printf (" Initial Values ​​of Array B Are: / n "); for (i = 0; i <5; i ) Printf ("% D", B [I]); NZP (b); Printf ("/ NLAST VALUES OF ARRAY B Are: / n"); for (i = 0; i <5; i ) PRINTF ("% D", B [I]);} This program is changed from the example 5.6 program, the length of the NZP function is changed to 8. In the function body, the loop condition of the FOR statement is also changed to i <8. Therefore, the length of the shape parameter group A and the real parameter group B are inconsistent. Compilation can pass, but from the results, the elements A [5], A [6], A [7] of the array A, and A [7] are obviously meaningless. c. In the function-specific reference, it is allowed to give the length of the parallel parameter group, or use a variable to represent the number of array elements. For example, it can be written as: VOID NZP (INT A []) or Write as Void NZP (INT A [], INT N) where the length of the argument group A does not give the length, and the length of the array is dynamatically indicated by the n value. n The value is transmitted by the argument of the main adjustment function. Thus, Example 5.6 can also be changed to Example 5.7. [Example 5.7] VOID NZP (INT A [], INT N) {INT I; Printf ("/ NVALUES OF ARRAY A Are: / n"); for (i = 0; I

The C language does not allow nested function definitions. Therefore, each function is parallel, there is no problem with the previous function and the next level function. However, C language allows calls to another function to occur in a definition of a function. This will appear nested calls for functions. That is, other functions are called again in the modulated function. This is similar to the situations of subroutine in other languages. Its relationship can be represented as shown in Figure 5.2. Figure 5.2 shows the two-layer nesting case. Its execution process is: When performing a statement that calls A function in the main function, turn around to execute a function, when the B function is called in the A function, turn the B function, the B function is executed, the breakpoint returns a function, continue Execute, the A function is executed to return the breakpoint that returns the main function to continue execution. [Example 5.8] Calculate S = 22! 32! This question can be written two functions, one is used to calculate the function F1 of the square value, and the other is the function F2 used to calculate the line. The main function pioneering F1 calculates the square value, and then in the F1, the square value is intern parameters, and F2 calculates the value of the stage, then returns F1, then returns the main function, and calculates the accumulation and calculation in the loop program. Long F1 (INT P) {INT K; Long R; Long F2 (int); k = p * p; r = f2 (k); RETURN R;} long f2 (int {long c = 1; int i ; for (i = 1; i <= q; i ) c = c * i; return C;} main () {INT i; long s = 0; for (i = 2; i <= 3; i ) s = S F1 (i); Printf ("/ ns =% ld / n", s);} long f1 (int P) {... long f2 (int); r = f2 (k); ......} Long F2 (INT Q) {...} main () {... S = S F1 (i); ...} In the program, both functions F1 and F2 are long integer, all defined before the main function, so it doesn't Then, F1 and F2 are described again in the main function. In the main program, the execution cycle program sequentially uses the I value as the real parameter function F1. The call to the function F2 is generated in F1. At this time, the value of the 2 is turned into the adjustment F2, and the calculation of the I2 is completed in F2. F2 is executed to return the C value (ie, I2!) to F1, and then return to the main function to achieve accumulation. At this point, the requirements of the topic are implemented by the nested call of the function. Since the value is large, the functions of the function and some variables are explained as long integrity, otherwise the calculation error will result.

Recurns of functions

A function calls itself in its function body called recursive call. This function is called a recursive function. C language allows the recursive call of the function. In recursive calls, the main adjustment function is called a function. Performing a recursive function will repeat itself. Enter a new layer per call. For example, there is a function f as follows: INT f (int x) {int y; z = f (y); return z;} This function is a recursive function. But running this function will call itself endless, which is of course incorrect. In order to prevent recursion calls from being terminated without termination, there must be a means of terminating recursive calls in a function. Commonly used methods are to add conditions to meet certain conditions, they will no longer be recursively called, and then returned by layer. The execution process of recursive call is illustrated below. [Example 5.9] Calculate N! N! N! (N-1) is represented by the following formula: N! = 1 (n = 0, 1) n × (n-1)! (N> 1) can be programmed according to formula As follows: long ff (int N) {long f; if (n <0) Printf ("n <0, input error"); ELSE IF (n == 0 || n == 1) f = 1; Else F = ff (n-1) * n; return (f);} main () {int N; long y; printf ("/ ninput a inteer number: / n"); scanf ("% d", & n); Y = ff (n); Printf ("% D! =% ld", n, y);} long ff (int N) {... else f = ff (n-1) * n; ......} main ) {... y = ff (n); ...} The function ff given in the program is a recursive function. After the main function calls the FF, the function ff is entered, if n <0, n = 0 or N = 1 will end the function execution, otherwise the FF function itself is recursively called. Since the argumentation of each recursive call is N-1, that is, the value of N-1 is assigned to the ginsen N, and finally when the value of N-1 is 1, the value is called, the value of the value is 1, will Terminate the recursive. Then be returned by layer. Below we will explain the process later. Enter 5 when performing this program, namely 5 !. In the main function, the call statement is y = ff (5), after entering the FF function, since N = 5, not equal to 0 or 1, there should be f = ff (n-1) * n, ie f = ff (5-1) * 5. This statement is recursively called FF (4) on FF. The successive recursion is shown in Figure 5.3. After four recursive calls, the value of the FF function is changed to 1, so the recursive call will not continue to return to the main adjustment function layer by layer. FF (1) The function return value is 1, the return value of the FF (2) is 1 * 2 = 2, the return value of FF (3) is 2 * 3 = 6, the return value of FF (4) is 6 * 4 = 24, the last return value FF (5) is 24 * 5 = 120.

Example 5. 9 can also be done without recursive methods. If you can use a push method, you will be multiplied from 1 to 2, then multiplied by 3 ... until n. Turning method is more easily understood and implemented than recursive. However, some problems can only be implemented with a recursive algorithm. A typical problem is the Hanoi tower problem. [Example 5.10] Hanoi tower problem has three needles, A, B, and C. The A needle has a disk with 64 sizes, large, small, small. As shown in Figure 5.4. To move this 64 disc from the A needle, only one disk can be moved each time, and the move can be performed by means of a B. But at any time, the disc on any needle must keep the market under the small plate. Ask the step of moving. This topic algorithm is analyzed, and there is n plate on a. If n = 1, move the disc from a directly to C. If n = 2, then: 1. Move the N-1 (equal to 1) disk on the N-1 (equal to 1) to B; 2. Move the A disk on A to C; 3. Finally N-1 (equal to 1) disk moves to C. If n = 3, then: a. Moves N-1 (equal to 2, so as a n`) a disk (by means of c), the steps are as follows: (1) Put a N` -1 (equal to 1) disk is moved to C, see Figure 5.5 (b). (2) Moves a disc on A to B, as shown in Figure 5.5 (c) (3) Moves the Na '-1 (equal to 1) disk on C to B, see Figure 5.5 (d) B. Moves a disk on A to C, see Figure 5.5 (e) c. Move the N-1 (2, which make it n`) a disk to c (by means A), the steps are as follows: (1) Move the N`-1 (equal to 1) disk on B to a, see Figure 5.5 (f) (2) Moves a tray on B to C, see Figure 5.5 (g) (3) Moves N`-1 (equal to 1) disk on a to C, see Figure 5.5 (h). At this point, the movement of three discs is completed. As can be seen from the above analysis, when N is greater than or equal to 2, the process can be decomposed into three steps: the first step is moved on the N-1 disk on the A. The second step is one of A. The disk is moved to C; the third step is moved to C on the N-1 disk on B; one of the first steps and third steps are class. When n = 3, the first step and third steps are decomposed into three steps, that is, the N`-1 disk is moved from one needle to another, and the n `= N-1 here.

Obviously this is a recursive process, accordingly, the algorithm can be programmed: Move (int N, int x, int y, int Z) {if (n == 1) Printf ("% C ->% C / N", X, z); else {move (n-1, x, z, y); Printf ("% C ->% C / N", X, Z); Move (N-1, Y, X, Z );}} main () {INTH; Printf ("/ ninput number: / n"); scanf ("% D", & H); Printf ("THE Step to Moving% 2D Diskees: / N", H) ; Move (h, 'a', 'b', 'c');} Move (INT N, INT X, INT Y, INT Z) {if (n == 1) Printf ("% ->% C / N ", x, z); Else {Move (N-1, X, Z, Y); Printf ("% C ->% C / N ", X, Z); Move (N-1, Y , x, z);} main () {... Move (h, 'a', 'b', 'c');} It can be seen from the program that the MOVE function is a recursive function, it has four Guanji N, X, Y, Z. n represents the number of discs, X, Y, and Z represent three needles, respectively. The function of the MOVE function is to move the N disks on the X to Z. When n == 1, directly to the disk on the X to z, output x → z. If n! = 1 is divided into three steps: recursive calls the Move function, move the N-1 disk from X to Y; output X → z; recursive call MOVE function, move the N-1 disk from Y to Y z. In the recursive call, n = n-1, the value of n is successfully decremented, and when the last n = 1, the recursive is terminated, and the layer is returned. When N = 4, the result is input number: 4The Step to Moving 4 Diskees: a → ba → CB → CA → BC → AC → BA → BA → CA → CB → AC → AB → CA → BA → CB → C variable scope

When the metallin variable of the function is discussed, the metallin variable is only assigned memory cells during the call, and the call ends are released immediately. This indicates that the shape is only valid in the function, and the function cannot be used again. This range of variables is the scope of the variable. Not only for the ginseng variable, all the amounts in the C language have their own scope. Variable descriptions are different, and its domain is different. The variable in the C language can be divided into two types, namely local variables and global variables according to the scope of action.

First, local variables

Partial variables are also known as internal variables. Local variables are defined in the function. Its scope is limited to the function, and this variable is illegal after leaving the function. For example: INT F1 (INT A) / * function f1 * / {INT B, C; ...} A, B, C scope INT F2 (int X) / * function f2 * / {int y, z;} x , Y, Z scope main () {INT M, N;} M, n-based domain defines three variables in function F1, and A is ginseng, B, C is a general variable. In the range of F1, A, B, C are valid, or the domain of A, B, and C variables are limited to F1. The scope of the same, X, Y, and Z is limited to F2. The scope of M, N is limited to the main function. The following points are also described on the role of local variables:

1. Variables defined in the main function can only be used in the main function and cannot be used in other functions. At the same time, the variables defined in other functions are not used in the main function. Because the main function is also a function, it is parallel to other functions. This is different from other languages ​​and should pay attention.

2. Conversion variables are local variables belonging to the modulated function, and the real parameters are local variables belonging to the main adjustment function. 3. Allows the use of the same variable name in different functions, which represent different objects, allocate different units, and do not interfere with each other, and it will not be confused. As in Example 5.3, the variable names of the meticulum and the arctic, are N, which is completely allowed. 4. The variable can also be defined in the composite statement, and its scope is only within the composite statement. For example: main () {Int S, A; ... {INT B; s = a b; ... B action domain} ... S, A action domain} [Example 5.11] main () {INT i = 2, J = 3, k; k = i j; {INT K = 8; if (i == 3) Printf ("% d / n", k);} printf ("% d / n% d / n" , I, k);} main () {INT i = 2, j = 3, k; k = i j; {INT K = 8; if (i = 3) Printf ("% d / n", k PRINTF ("% D / N% D / N", I, K);} This program defines three variables of I, J, K in Main, where K is not assigned. A variable K has also been defined in the composite statement, and the first value is 8. It should be noted that these two K are not the same variable. The k works from the MAIN defined by the composite statement, while the complex statement is rooted by the K within the composite statement. Therefore, the k of the procedure of the program is defined by Main, and its value should be 5. The line 7 outputs the K value, the row works in the composite statement, and the K roofed by the K, which is 8, the output value is 8, the 9th line output I, K value. i is valid throughout the program, and the second line is assigned to 3, so the output is 3. The 9th line has been in addition to the composite statement, and the output K should be the K, which is defined by Main, which is obtained from the fourth line, so the output is 5.

Second, global variables

Global variables are also known as external variables, which are variables defined outside of the function. It does not belong to which function that belongs to a source file. Its scope is the entire source program. In the function, global variables are used, and it is generally written for global variables. Only global variables that have been explained in the function can be used. The set of global variables is extern. However, global variables defined before a function are not described in this function. For example: INT A, B; / * External variable * / void f1 () / * function f1 * / {...} float x, y; / * External variable * / int FZ () / * function fz * / {... ...} main () / * main function * / {...} / * Global variable x, y scope global variable A, B action domain * / From the previous example, it can be seen that all of the A, B, X, Y is functions External definition external variables are global variables. However, x, y is defined after the function f1, and in the F1, there is no description of X, Y, so they are invalid in F1. A, B defines the most in front of the source program, so it is also available in F1, F2, and Main.

[Example 5.12] Enter the length of the positive body L, W, H. The area of ​​the volume and three surfaces x * Y, X * z, Y * z. INT S1, S2, S3; INT VS (INT A, INT B, INT C) {INT V; V = A * B * C; S1 = A * B; S2 = B * C; S3 = A * C; Return v;} main () {Int v, L, W, h; printf ("/ ninput length, width and height / n"); scanf ("% D% D% D", & L, & W, & H); v = VS (L, W, H); Printf ("V =% D S1 =% D S2 =% D S3 =% D / N", V, S1, S2, S3);} These are defined in this program three The external variables S1, S2, S3 are used to store three areas, and their scope is the entire program. The function VS is used to seek a positive square and three area, and the return value of the function is volume V. The main function is used to complete the input and result output of length wide high. Since the C language specified function return value only one, use external variables in a good way when it is necessary to increase the return data of the function. In this example, if an external variable is not used, four values ​​of V, S1, S2, S3 are not possible in the main function. The external variable is used, and S1, S2, and S3 value acquired in function Vs are still valid in main. Therefore, external variables are an effective means of implementing data communication between functions. There is also the following description for global variables: 1. For the definition and description of local variables, it can be distinct. For external variables, otherwise, the definition of external variables and the instructions of external variables are not one thing. External variable definitions must be outside all functions and can only be defined once. Its general form is: [Extern] Type Description Variable name, variable name ... The externs in which square brackets can save. For example: INT A, B; equivalent to: Extern Int A, B; and external variable descriptions There is a general form of multiple times, and external variables may occur in the entire program in each function to use the external variable. : Extern type indicator variable name, variable name, ...; external variables have allocated memory cells when defined, and external variable definitions can be initially assigned, and external variables cannot be assigned to the initial value, but it is indicated that in the function. External variables.

2. External variables can enhance the data links between the function modules, but make functions depend on these variables, thus reduced the independence of the function. This is unfavorable from the viewpoint of modular programming, so try not to use global variables when unnecessary.

3. In the same source file, the global variables and local variables are allowed. The global variable does not work in the scope of local variables. [Example 5.13] INT VS (INT L, INT W) {EXTERN INTH; INT V; V = L * W * h; returnv;} main () {EXTERN INT W, H; int L = 5; Printf "v =% D", VS (L, W));} int L = 3, W = 4, h = 5; in this case, the external variable is finally defined, so the outside of the previous function Variables must be described. External variables L, W and VS functions of VS L, W. The external variables have been initially assigned, and the L is initialized in the MIAN function. When the program is executed, the VS function is called in the printf statement. The value of the actors should be the L value defined in the main, equal to 5, and the external variable L does not work in the main parameters; the value of the argument W is the value of the external variable W. For 4, the two values ​​transmitted after entering VS, the H is used in the WVS function, which is 5, and the value is 5, the calculation result of V is 100, and the main function is returned. Variable storage Types variable range of variables, the essence is the same as the storage type of the variable. The so-called storage type refers to the way variables take up memory space, also known as storage. The storage mode of the variable can be divided into "static storage" and "dynamic storage".

Static storage variables are typically determined when the variable is defined and the storage unit is kept unchanged until the entire program ends. 5.5.1 The global variables described in Sections are such storage. Dynamic storage variables are allocated in the program execution, and the storage unit is allocated, and then release it immediately. A typical example is the formal parameters of the function, and does not give the formation of the storage unit when the function is defined, but is allocated when the function is called, and the call function is released immediately. If a function is called multiple times, repeatedly assign, release the memory cell of the mediate amount. From the above analysis, the static storage variable is always existing, and when the dynamic storage variable is present, it disappears. We also put this life of the variable variables due to variable storage methods. The survival period represents the time of the variable. The survival and scope are two different perspectives from time and space to describe the characteristics of the variable, both of which communicate and distinct. Which storage method is a variable that does not be judged from its role domain, and there should be a clear storage type description.

In the C language, the storage type of the variable has the following four: Auto Auto Auto Variables Register Register Variable External Variable Static Static Variable Auto Variables and Register Variables belong to dynamic storage, external variables, and static variables belong to static storage. After introducing the storage type of the variable, you can know that the description of a variable should not only indicate its data type, but also its storage type. Therefore, the complete form of variables should be: Storage Type Description Data Type Description Variable Name, Variable Name ...; for example: Static Int A, B; Description A, B is a static type variable AUTO CHAR C1, C2; Description C1, C2 For the automatic character variable static int A [5] = {1, 2, 3, 4, 5}; Description A is the static integer array external Int x, y; Description x, y is the external integer variable, the above four Type of storage:

First, the type of automatic variable is an auto. This type of storage is the most widely used type in the C language program. C language regulations, the variables in which the unfained storage type descriptions are treated as auto variables, that is, auto variables can be omitted. The variables defined in the procedures in the previous chapters are automatic variables that are not stored. For example: {INT I, J, K; CHAR C; ...} equivalent to: {Auto Int i, j, k; auto char c; ...} Automatic variable has the following features: 1. The function of automatic variables only Limited to the individual defined for this variable. The auto variables defined in the function are valid only in this function. 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 action domain * / ...} / * a, x, y - Domain * / 2. Automatic variable belongs to dynamics The storage method is only used to assign a storage unit when the function is used to define the variable, and start its survival. The function call ends, releases the storage unit, and end the survival period. Therefore, the value of the automatic variable cannot be retained after the function call. The auto variables defined in the composite statement cannot be used after exiting the composite statement, otherwise an error will cause an error. For example, the following procedure: 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 =% DP =% 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 =% dp =% d / n ", s, p );} S, P is the automatic variable defined within the composite statement, and can only be valid within the composite statement. The 9th line of the program is the value of S, P after exiting the composite statement, which will obviously cause errors.

3. Since the scope of the automatic variable is limited to defining the individual (function or complex statement) within the individual (function or complex statement), different individuals are allowed to use the same name variables without confusion. Even the auto variables defined within the function can also be the same name as the auto variable defined in the composite statement within the function. Example 5.14 shows this situation. [Example 5.14] 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 =% DP =% D / N", S, P);} printf ("s =% DP =% D / N ", s, p);} This program defines the variables S, P is automatic variables twice in the main function and the composite statement. According to the provisions of the C language, within the composite statement, the S, P works in the composite statement, so the value of S should be a value of A A, P, which is a * a. The S, P should be the S, P, which is defined by the MAIN, which is given to 100 when it is initialized. From the output result, two S and two P although the variable name is the same, but it is two different variables.

4. Automatic variables of the structure type, such as array, etc., etc., cannot be assigned.

Second, the type of external variable external variable is an extern.

External variables have been described when the global variables are described earlier. Here, there are several features of the external variables here: 1. External variables and global variables are a sub-law of two different angles of the same type variable. The global change is proposed from its scope, and the external variable is proposed from its storage method, indicating its survival. 2. When a source program consists of several source files, the external variables defined in one source file are also valid in other source files. For example, there is a source program consisting of source files f1.c and f2.c: f1.cint a, b; / * External variable definition * / char C; / * External variable definition * / main () {...} f2. CEXTERN INT A, B; / * External Variable Description * / Extern CHAR C; / * External Variable Description * / Func (INT X, Y) {...} It is used in two files in F1.c and F2.c. A, B, C three variables. Both A, B, and C are defined as external variables in the f1.c file. In the f2.c file, use external variables as external variables in the f2.c file, indicating that these variables are defined in other files and the types and variable names of these variables, and the compilation system will no longer allocate memory space for them. For external variables of the structure type, such as an array or the like may be initialized in an explanation. If the initial value is not assigned, the system automatically defines its initial value of 0.

Third, static variable

The type of static variable is static. Static variables are of course a static storage method, but it is not necessarily static variables. For example, although the external variable belongs to a static storage method, it is not necessarily a static variable, and must be defined by static to become a static external variable. Or static global variables. For automatic variables, it has been described in front of the dynamic storage. However, it is also possible to define static auto variables, or static partial variables, thereby being static storage. From this point, a variable can be described again by STATIC and change its original storage.

1. Static local variables are coupled to the Static representation before the local variables. For example: Static Int A, B; Static Float Array [5] = {1, 2, 3, 4, 5}; Static partial variables belong to static storage, with the following features: (1) Static local variables define within functions However, it is not like an automatic variable, when the call is present, it disappears when exiting the function. The static local variable always exists, which means that its survival is the entire source program.

(2) Although the survival of static local variables is the entire source program, its scope is still the same as the automatic variable, that is, the variable can only be used within a function of defining the variable. After exiting the function, although the variable continues to exist, it cannot be used.

(3) Allow the first value of the static part of the structure class. In an array chapter, the array has been described when the array is initialized. If the initial value is not assigned, the system is automatically assigned with 0 values.

(4) If a static partial variable of the basic type is not assigned at an explanation, the system automatically assigns 0 values. The value of the automatic variable is not assigned, and its value is not. According to the characteristics of static partial variables, it can be seen that it is an amount of a living period as the entire source program. Although it cannot be used after leaving its function, if it is called again to define its function, it can continue to use, and save the value left after the previous call. Therefore, when a function is called multiple times and requires a statically local variable to be considered when retaining certain variables between calls. Although the above objects can be reached with global variables, global variables sometimes cause unexpected side effects, so it is still advisable to employ 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);} Defined function f, where variable j illustrates automatic variables and assuming the initial value 0. When f is called multiple times in the main, the j be all assigned to 0, so each output value is 1. Now change J to static local variables, the procedure is as follows: main () {Int i; void f (); for (i = 1; i <= 5;}) f ();} void f () {Static Int J = 0; J; Printf ("% d / n", j);} void f () {static int j = 0; J; Printf ("% d / n", j);} Due to J For static variables, the output value becomes accumulated in each time the value is retained each time the value is retained and the output value is accumulated. Readers can analyze their execution processes themselves. 2. Static global variable global variable (external variable) The preceding crowns constitutes a static global variable with Static. The global variable itself is a static storage method, and the static global variable is of course still static storage. Both of these are not different in storage. Although the difference between the two is the scope of the non-static global variable is the entire source program, when a source program consists of multiple source files, non-static global variables are valid in each source file. Static global variables limits its role, that is, it is only valid within the source file that defines the variable, and it cannot be used in other source files of the same source program. Since the scope of the static global variable is limited to one source file, it can only be used for functions within the source file, so it is possible to avoid errors in other source files. From the above analysis, it can be seen that the local variable is changed to a static variable, which has changed its storage mode. After changing the global variable to a static variable, it is changed its scope, limiting its range. Therefore, the role of Static this specifier is different from different places. It should be paid attention to.

Fourth, register variable

All of the above variables are stored in memory, so when it is frequently read or written to a variable, it is necessary to repeatedly access the internal memory, thereby spend a lot of access times. To this end, the C language provides another variable, namely the register variable. Such variables are stored in the registers of the CPU, and the memory is not needed, and it is read directly from the register, which can improve efficiency. The indicator of the register variable is Register. The loop control variables with more cycles and the repeated variables in the cycle can be defined as register variables. [Example 5.16] Seeking σ200i = 1Imain () {register i, s = 0; for (i = 1; i <= 200; i ) s = S I; Printf ("s =% D / N", S );} This program is 200 times, I and S will be frequently used, so it can be defined as a register variable. The following points are also described in the register variable: 1. Only partial auto variables and form parameters can be defined as register variables. Because the register variable belongs to the dynamic storage. Any amount that needs to be stored in a static storage cannot be defined as a register variable.

2. In the C language used on the microcomputer of Turbo C, MS C, in fact, the register variable is treated as an automatic variable. Therefore, the speed does not improve. The register variable is allowed in the program is only consistent with the standard C. 3. Even the machine can really use the register variable, the number of register variables is also limited because the number of registers in the CPU is limited.

Internal function and external functions

Once the function is defined, it can be called by other functions. However, when a source program consists of multiple source files, can the functions defined in one source file be called by the function in other source files? To this end, the C language divides the function into two categories:

First, internal functions

If the function defined in a source file can only be called by the function in this document, which cannot be called by a function in other files in the same source program, which is called internal functions. The general form of defining internal functions is: Static Type Desifferent Function Name (Dielectric INT F (int A, int b) internal function is also known as static functions. However, the meaning of static static this is no means a storage method, but refers to the scope of the call to the function is limited to this document. Therefore, the static function that defines the same name in different source files will not cause confusion.

Second, the external function external function is valid throughout the source program, the general form of the definition is: Extern type indicator function (Dielectric reference) For example: Extern Int f (int A, int b), if there is no in the function definition Note EXTERN or STATIIC is implied to Extern. When you call an external function defined in another source file in a function of a source file, you should use extern to indicate that the modulated function is an external function. For example: f1.c (Source File 1) Main () {Extern INT F1 (INT i); / * External Function Description, indicating that the F1 function is in other source files * / ...} f2.c (Source File 2) Extern INT F1 (INT i); / * External function definition * / {...}

转载请注明原文地址:https://www.9cbs.com/read-126692.html

New Post(0)