Functions or procedures can haveDefault Parameter(Default parameters), As in its name, if a function or process does not specify a parameter during call, it will provide a default value for the function.
To declare a process or function with a default value, the parameter type is followed by an equal sign and default value.
The following example shows a complete example to implement an addition program. By default, two numbers are added, but three numbers can also be added.
1,Create a console application.
2,Enter the following code in the code to create an addints function to add numbers:
Program project1; {$ apptype console} uses sysutils; {default value of the third parameter I3 in the addints function is 0} function addints (I1, I2: integer; I3: integer = 0 ): integer; begin result: = I1 + I2 + I3; end; var I1, I2, I3: integer; JG: integer; begin I1: = 123; I2: = 321; I3: = 555; JG: = addints (I1, I2); {Add two numbers I1 + I2} writeln (inttostr (I1) + '+ inttostr (I2) + '=' + inttostr (JG); {output I1 + I2 = JG} JG: = addints (I1, I2, I3 ); {implement three-digit addition I1 + I2 + I3} writeln (inttostr (I1) + '+ inttostr (I2) +' + inttostr (I3) + '=' + inttostr (JG); {output I1 + I2 + I3 = JG} readln; end.
3,The running result is as follows:
4,The biggest advantage of default parameters is that you do not have to worry about backward compatibility when adding features to an existing process and function, just like the aboveAddintsFunction, add a third parameter with the default valueAddintsFunction expansion without worrying about its compatibility.
Note
Any default parameter can only be placed at the end of the function or process parameter table. The following code is an invalid function declaration:
procedure MyProcedure(X: Integer; Y: Integer = 10; Z: Integer);
Compile the above statement and report"Default Value required for 'Z'"Error. If you want to successfully compile this function declaration, you must move the default parameter to the end of the parameter table, as shown below:
procedure MyProcedure(X: Integer; Z: Integer; Y: Integer = 10);
The above code has passed the test in Delphi7.