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, Variant
s, and
large records and sets are passed as a hidden var
parameter.
Tips and Tricks
Think of the
Result
variable as avar
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 namedResult
, 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 |
Get Delphi in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.