1.8 process and Function
Processes and functions are statement blocks that implement certain functions and are specific functional units in the program. It can be called elsewhere in the program or recursively. The difference between a process and a function is that a process has no return value, but a function has a return value.
1. Process and Function Definition
The process and function definition includes the process prototype or function prototype, process body or function body definition. The process is defined as follows:
procedure ProcedureName(ParameterList); directives;var LocalDeclarations;begin statementsend;
Procedurename is a process name and a valid identifier. Parameterlist is a process parameter list. You must specify the number and Data Type of parameters. Directives is some directive words about the function. If multiple statements are set, they should be separated by semicolons. Localdeclarations defines some temporary variables to be used in this function, which are also called local variables. Between In in and end is a series of statements that implement specific functions during the process call. Parameterlist, directives, localdeclarations, and statements are optional.
The function definition is very similar to the process. It only uses different Reserved Words and has an additional return value type. The specific form is as follows:
function FunctionName(ParameterList): ReturnType; directives;var LocalDeclarations;begin statementsend;
You can assign a value to the result variable. If the function body contains some branch statements generated by judgment, you must set the return value in each branch. The next operation is usually determined based on the return value of the function. Note that this
Is different from Visual C and Visual C ++. If you assign a value to result, the function will not end.
2. Parameters
When a function is defined, parameters in the parameter list are called form parameters. When a function is called, parameters in the parameter list are called real parameters. In the defined function prototype, multiple parameters are separated by semicolons. Parameters of the same type can be put together and separated by commas. When a function is called, multiple parameters in the function prototype are separated by commas.
In general, the exact match between the form parameter list and the real parameter list means that the number of parameters is the same, and the Data Types of the ordered parameters are also the same. For common functions, if the compiler finds that the data type of the real parameter does not match the data type of the form parameter, the Data Type of the real parameter is upgraded once or multiple times ", for example, convert the integer type to the double type. You can specify the default value for the process and function parameters. The parameter that specifies the default value should be placed at the back of the parameter list, but the parameter that does not specify the default value should be placed before the parameter list
. When calling a function, you can specify a new value for the parameter with the default value. In the function body, each statement uses the specified new value. If no new value is specified, the default value is used. Similarly, if there are multiple parameters with default values set
The new value can be specified only after the new value is specified.
The following example defines an outputnum function that can output a floating point number at the specified precision. In this example, you can use the following parameters in the function:
Program project1; {$ apptype console} uses sysutils; // to use the formatfunction outputnum (number: Double; N: integer = 5): Boolean; var STR: string; // The output content begin if n <=-1 then // The number of digits after the decimal point must be greater than or equal to 0 begin result: = false; exit; // exit the display function end else begin // sets the display format STR: = format ('% *. * F', [10, N, number]); Result: = true; writeln (STR); // display data end; begin outputnum (12.345 ); // The default value of N is 5 outputnum (). // The parameter specifies the data type. Upgrade // the following code is incorrect, so block it. // outputnum (123.456789, 9.13 ); // The parameter cannot degrade the data type. // you can determine the next operation based on the return value of the function. If outputnum (123.456789,-3) = false then writeln ('output failed. '); Readln; end.
The running result is as follows:
12.34500123.000 output failed.
Here are some notes:
- To use the Function Format, you must include the sysutils unit in the uses statement.
- Because the number of digits after the decimal point cannot be set to a negative number, when a negative number occurs, the outputnum function returns false and calls the exit function to exit the outputnum function immediately.
- In the statement outputnum (123), first convert the integer constant to a floating point constant, and then pass the parameter.
There are three common parameters:Numeric Parameter,Variable parametersAndConstant Parameters.
Only the value of the parameter is changed during the running process, and the value of the parameter is not changed. That is, the value of the parameter cannot be passed outside the process. Example:
procedure Calculate(CalNo:Integer);begin CalNo := CalNo*10;end;
Use the following routine to call the calculate function:
Calculate(Number);
After entering the calculate function, the number real parameter will be copied to the form parameter Calno. In this process, Calno is increased by 10 times, but it is not passed out, so the number value has not changed. Parameters and real parameters occupy different memory addresses. When a process or function is called, the values of real parameters are copied to the memory occupied by the parameters. Therefore, after jumping out of the process or function, the values of the form parameter and the real parameter are different, but the values of the real parameter do not change.
If you want to change the input parameter value, you need to use the variable parameter, that is, add the reserved word var before the form parameter in the parameter table of the called program. For example:
procedure Calculate(var CalNo : Integer);
Then Calno does not occupy a position in the memory, but points to the real parameter number. When a real parameter is passed, any changes made to the form parameter will be reflected in the real parameter, because the two parameters point to the same address. Add var before the parameter Calno in the previous routine and call it with the same program. The calculation result is displayed in the 2nd edit box, enlarge the values in the 1st edit boxes by 10 times. In this case, the parameters Calno and number are 10 times the initial value of nnmber.
If you do not need to change the value of the form parameter during the process or function execution, the most secure way is to use constant parameters. Adding the reserved word const before the parameter name of the parameter table can make a form parameter a constant parameter. Using constant parameters instead of numeric parameters can protect user parameters so that users do not accidentally assign new values to this parameter if they do not want to change the value. The following example can help readers better understand the problem:
Program project1; {$ apptype console} type pinteger = ^ integer; // define the pointer type procedure p1 (var n: integer); // reference the parameter to pass begin n: = n + 1; end; Procedure P2 (N: integer); // pass the begin n: = n + 2; end; Procedure P3 (Pt: pinteger ); // pass the pointer parameter begin PT ^: = PT ^ + 3; end; var I: integer; begin I: = 1; P1 (I ); // increase the value of I by 1 writeln ('I:', I); P2 (I); // you want to add I to 2, but writeln ('I: ', I); P3 (@ I); // Add I to 3 writeln (' I: ', I); readln; end.
The running result is as follows:
i:2i:2i:5
Here are some notes:
- At the beginning, the value of variable I is 1. After processing in the P1 process, I is added to 1, so the value of the first 1st I is 2. In this case, the reference parameter is used for transmission.
- In P2, the value of the parameter is increased by 2. In fact, I does not increase, so the value of the 2nd I is still 2. In this case, the return value of the function can be used normally, for example:
Result:=N+2;
When calling a function:
i:=P2(i);
- In the process P3, the pointer of variable I is passed, so the operation is for I, and the value of I is 5 for 3rd Times.
3. Procedure and function call conventions
When calling a process or function, if the parameter list contains multiple parameters, the order in which the parameters are passed to the process or function will affect the result. For different languages, the order in which parameters are transmitted is different: Pascal uses the order from left to right, the C language is transmitted from the right to the left.
In order to determine the sequence of transmission, you can use the directive to specify the sequence of transmission in the direves ves part during the process or function definition. Online Help data from Delphi is shown in Table 1-13, which lists the directives that can be used in the direves ves section about function call conventions.
Table 1-13 commands used to define a procedure and function for a call Convention
| Directive command |
Register |
Pascal |
Stdcall |
Safecall |
Cdecl |
| Parameter transfer order |
From left to right |
From left to right |
From right to left |
From right to left |
From right to left |
The following example shows the order in which parameters are transmitted:
Program project1; {$ apptype console} function P1: integer; // this function will be used as the 1st parameter of the getmax function begin writeln ('p1'); Result: = 0; end; function P2: integer; // this function will be used as the first parameter of the getmax function, begin writeln ('p2'); Result: = 1; end; // The parameter transmission method uses the Pascal function getmax (N1: integer; N2: integer): integer; Pascal; begin result: = N1 + N2; end; begin getmax (P1, p2); end.
The running result is as follows:
If you change the direves ves part of the getmax function definition from Pascal to stdcall, the running result is:
P2P1
You can modify the direves ves section of the getmax function definition to other values in Table 1-13. The test results are consistent.
4. Process and function Overloading
You can give different procedures or functions the same name within the same scope of action. This phenomenon is called overload. This makes programming more convenient. In the case of heavy load, it is determined which process or function is used based on the consistency of the form parameters and real parameters, that is, the number of parameters, parameter types, and the order between them, there is no function call that satisfies two overloaded functions. In addition, the heavy-duty function must use the overload command to describe the function. Different return value types cannot be used as the basis for heavy-duty functions. The following two functions
Is the overload function:
Function average (A: integer; B: integer): Double; overload; // calculate the average value of Integer Data function average (A: Double; B: Double): Double; overload; // average value of realistic data
The following two statements call different functions:
Average (3.7, 4.6); // call 2nd overloaded functions average (1st); // call overloaded functions
If another overload function is defined as follows:
Function average (A, B: Double; C: Double = 0.0): Double; overload; // calculate the average value of three real numbers.
As shown in the preceding example, although the number of parameters is different from the preceding two, a default value is set for the 3rd parameters.
When the parameter is called as the statement average (1.1, 2.2), the compilation system does not know which overload function should be used, because 2nd overload Functions
Both the number and the number of 3rd overload functions can meet the requirements, resulting in a compilation error.
5. recursive function call
In Object Pascal, the process or function must be described before calling. The preceding rules are exceptional in recursive calls. The so-called recursive call refers to the situation in which function a calls function B, and function B calls function A, or a special situation in which a function calls itself. In recursive calls, the function must be prefixed, that is, the reserved word forward is added at the end of the function or process title. The following is a typical example of recursive calling:
Program project1; {$ apptype console} var ALPHA: integer; Procedure Test2 (var a: integer); forward; // Test2 is described as the pre-process procedure test1 (var: integer); begin A: = A-1; if a> 0 then Test2 (a); // call the unexecuted process Test2 writeln (a); end; procedure Test2 (var a: integer); // The execution part of Test2, as described above, is begin A: = A Div 2; if a> 0 then test1 (); // call the executed process test1end; begin Alpha: = 15; // assign the initial value test1 (alpha) to Alpha; // call test1 1st times and start end recursively.
At the beginning of the program, the program assigns an initial value to Alpha, and implements a recursive call that first removes 1 and then removes 2 until Alpha is less than 0.
1.9 standardized naming
In the process of system development, it is often necessary to name variables, classes, objects, functions and files. Generally, a complete and practical naming rule must be developed at the development requirement or design stage. In this way, the system development efficiency can be greatly improved, and the interfaces between different modules can be easily maintained.
When naming rules are formulated, a basic principle is convenient to use, easy to maintain, and uniform style. Pay attention to the following points:
- You must use English words instead of Chinese pinyin. In particular, do not use a combination of 1st Chinese pinyin letters. When naming English words, use unified, simple, and appropriate words as much as possible, and use complete words or syllables as much as possible.
- Some names can be combined with several English words. During the combination process, try not to use underscores to separate words. It is best to use case-insensitive mixed writing.
- Reserved and Directive words can all be in lowercase, while some constant names can all be in uppercase.
- Some names can be combined with "Verb + object" or "Object + verb. In general, "Verb + object" is more in line with common syntax habits. No matter which method is used, it should be unified as a whole.
- In some cases, we need to consider the unification of the integrated development environment with Delphi. For example, in the integrated development environment of Delphi, the names of common classes generally start with t, and the names of exception classes generally start with E.
- When naming a menu command ID, you should include the name of the menu item. For example, for menu commands in the "file" menu item, you can name the identification number fileopen or fileclose.
- For some names that represent the meaning of a set, you can use the plural form of a noun. For example, you can use Windows instead of windowcollection for a set of windows.
Reference: http://chanlei001.blog.163.com/blog/static/3403066420117261154351
Http://www.cnblogs.com/del/archive/2007/12/04/982167.html
Http://blog.csdn.net/hudie1234567/article/details/6403419