Name

Result Variable

Syntax

var Result: Function return type;

Description

Delphi automatically creates a variable named Result in every function. The variable’s type is the return type of the function. The value that Result has when the function returns is the function’s return value.

In standard Pascal, a function specifies its return value by assigning to a pseudo-variable whose name is the same as the function’s. The Result variable works similarly, but because it behaves as a real variable, you can use it in expressions—something you cannot do with the function name.

Functions return ordinal values, pointers, and small records or sets in EAX, and floating-point values on the FPU stack. Strings, dynamic arrays, Variants, and large records and sets are passed as a hidden var parameter.

Tips and Tricks

  • Think of the Result variable as a var parameter. It does not have any valid value when the function begins, so you must initialize it or otherwise ensure that it has a meaningful value.

  • Delphi declares the Result variable even if you do not use it. If you try to declare a local variable named Result, the compiler issues an error (Identifier redeclared) message.

Example

// Return a reversed copy of S.
function Reverse(const S: string): string;
var
  I, J: Integer;
begin
  I := 1;
  J := Length(S);
  SetLength(Result, J);
  while I <= J do
  begin
    Result[I] := S[J];
    Result[J] := S[I];
    Inc(I);
    Dec(J);
  end;
end;

See Also

Function Keyword, Out Directive
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset