How to Return Multiple Values from a Delphi Routine

Routines or most properly known as procedures or functions, are one of the most common constructs when it comes to making Delphi applications. They are statement blocks that you call from different locations in a program. In simpler terms, a procedure is a kind of routine that doesn’t return any value while a function, on the other hand, returns a certain value.

 

Return Multiple Values from a Delphi Routine
Return Multiple Values from a Delphi Routine

 

A function’s return value is defined by the return type which, in most cases, would return either an integer, string, Boolean or some other type. Even if your function returns a string list, it will still return a single value, which is one instance of the string list. Delphi Routines have different types; Routine, Method Pointer, Method, Event Delegate and Anonymous Method.

 

Most programmers think that a function is limited to return only a single value. A function, ridiculous as it seems, can also return multiple values.

 

Take this one function as an example.

 

 

function PositiveReciprocal(const valueIn : integer; var valueOut : real): boolean;

 

This one returns a Boolean (it is a true-false statement) value. The VAR parameter, on the other hand, is passed to the function by reference, meaning that if the function changes the parameter’s value, the function will change the variable’s value for the parameter.

 

 

function PositiveReciprocal(const valueIn: integer; var valueOut: real): boolean;begin  result := valueIn > 0;   if result then valueOut := 1 / valueIn;end;

 

The valueIn is passed as a constant parameter and is treated as read-only. The function in no way can alter it. If it’s greater than zero, the valueOut parameter’s reciprocal value is assigned to that. The function’s results, as it is, will become true. If the valueIn is <=0 then the function returns a false statement and valueOut isn’t changed. Therefore, in this case, the function will return two values.

 

Comments

comments


Posted

in

by

Tags: