You can
specify default parameter values in a procedure or function heading. Default
values are allowed only for typed const and value parameters. To provide
a default value, end the parameter declaration with the = symbol followed by a
constant expression that is assignment-compatible with the parameter’s type.
For
example, given the declaration
procedure
FillArray(A: array of Integer; Value: Integer = 0);
the following procedure calls are
equivalent.
FillArray(MyArray);
FillArray(MyArray,
0);
A
multiple-parameter declaration cannot specify a default value. Thus, while
function
MyFunction(X: Real = 3.5; Y: Real = 3.5): Real;
is legal,
function
MyFunction(X, Y: Real = 3.5): Real;
// syntax error
is not.
Parameters
with default values must occur at the end of the parameter list. That is, all
parameters following the first declared default value must also have default
values. So the following declaration is illegal.
procedure
MyProcedure(I: Integer = 1; S: string); // syntax error
Default values specified in a
procedural type override those specified in an actual routine. Thus, given the
declarations
type
TResizer = function(X: Real; Y: Real = 1.0): Real;
function
Resizer(X: Real; Y: Real = 2.0): Real;
var
F: TResizer;
N: Real;
the statements
F :=
Resizer;
F(N);
result in the values (N, 1.0) being passed
to Resizer.
Default
parameters are limited to values that can be specified by a constant
expression. Hence parameters of a dynamic-array, procedural, class,
class-reference, or interface type can have no value other than nil as
their default. Parameters of a record, variant, file, static-array, or object
type cannot have default values at all.
For
information about calling routines with default parameter values, see Calling procedures and
functions.
Default
parameters and overloaded routines
Default parameters in forward and interface declarations
Declaring procedures and
functions: Overview
在过程或函数首部可以指定缺省参数的值。缺省值仅允许用于有类型的常量参数(const参数)和值参数(value参数)。要提供缺省值,需要在参数声明的末尾使用等号(=)并跟随一个与参数类型赋值兼容的常量表达式。
例如,给出如下声明
procedure
FillArray(A: array of Integer; Value: Integer = 0);
下面两个过程调用是等价的:
FillArray(MyArray);
FillArray(MyArray,
0);
多个参数的声明不能指定一个缺省值。因此,下面的声明
function
MyFunction(X: Real = 3.5; Y: Real = 3.5): Real;
是合法的,而下面的声明
function
MyFunction(X, Y: Real = 3.5): Real;
//语法错误
是不合法的。
含有缺省值的参数必需出现参数列表的末尾。简言之,跟随在第一个声明了缺省值的参数之后的所有参数都必需也有缺省值。因此,下面的声明是不合法的:
procedure
MyProcedure(I: Integer = 1; S: string); //语法错误
在程序型类型中指定的缺省值将覆盖在实际例程中指定的缺省值。因此,对于如下声明
type
TResizer = function(X: Real; Y: Real = 1.0): Real;
function
Resizer(X: Real; Y: Real = 2.0): Real;
var
F: TResizer;
N: Real;
下列语句
F :=
Resizer;
F(N);
的结果是参数值 (N, 1.0) 被传递给函数Resizer。
缺省参数的值必需以常量表达式指定。因此,动态数组、程序型、类、类引用或接口等类型,它们作为参数时只能指定nil作为缺省值。至于记录、变体、文件、静态数组或对象等类型,它们作为参数时则根本不能有缺省值。
有关调用含有缺省参数值例程的更多信息,见调用过程和函数。