A function declaration is like a procedure declaration except that it specifies a return type and a return value. Function declarations have the form
function functionName(parameterList): returnType; directives;
localDeclarations;
begin
statements
end;
where functionName is any valid identifier, returnType is any type, statements is a sequence of statements that execute when the function is called, and (parameterList), directives;, and localDeclarations; are optional.
·
For information about the parameterList, see Parameters.
·
For information about localDeclarations, which declares local identifiers, see Local declarations.
The function's statement block is governed by the same rules that apply to procedures. Within the statement block, you can use variables and other identifiers declared in the localDeclarations part of the function, parameter names from the parameter list, and any identifiers within whose scope the function declaration falls. In addition, the function name itself acts as a special variable that holds the function's return value, as does the predefined variable Result.
For example,
function WF: Integer;
begin
WF := 17;
end;
defines a constant function called WF that takes no parameters and always returns the integer value 17. This declaration is equivalent to
function WF: Integer;
begin
Result := 17;
end;
Here is a more complicated function declaration:
function Max(A: arrayof Real; N: Integer): Real;
var
X: Real;
I: Integer;
begin
X := A[0];
for I := 1to N - 1do if X < A[I] then X := A[I];
Max := X;
end;
You can assign a value to Result or to the function name repeatedly within a statement block, as long as you assign only values that match the declared return type. When execution of the function terminates, whatever value was last assigned to Result or to the function name becomes the function's return value. For example,
function Power(X: Real; Y: Integer): Real;
var
I: Integer;
begin
Result := 1.0;
I := Y;
while I > 0do begin if Odd(I) then Result := Result * X;
I := I div2;
X := Sqr(X);
end;
end;
Result and the function name always represent the same value. Hence
function MyFunction: Integer;
begin
MyFunction := 5;
Result := Result * 2;
MyFunction := Result + 1;
end;
returns the value 11. But Result is not completely interchangeable with the function name. When the function name appears on the left side of an assignment statement, the compiler assumes that it is being used (like Result) to track the return value; when the function name appears anywhere else in the statement block, the compiler interprets it as a recursive call to the function itself. Result, on the other hand, can be used as a variable in operations, typecasts, set constructors, indexes, and calls to other routines.
Result is implicitly declared in every function. Do not try to redeclare it.
If execution terminates without an assignment being made to Result or the function name, then the function's return value is undefined.