[fpc-pascal] function returning a record vs paramaters

Anton Tichawa anton.tichawa at chello.at
Sat Jul 9 22:38:33 CEST 2005


L505 wrote:

>When a function requires that more than one value must be returned, what are the
>advantages of returning one of these values in a paramater versus using a record
>that contains all the data?
>
>Example:
>A function needs to return an integer, string, and boolean.  Why not just return
>a record containing an integer, string, and boolean?
>
>  
>
When the integer, string, and boolean are logically related, and are 
typically assigned, copied, allocated, stored or else processed as a 
whole block, a record should be used anyway.

>Advantages of records:
> Surely records are much more legible code design than parameters.
>
>  
>
Yes, especially in function calls, as in your example.

>Disadvantages of records:
> ???
> Are paramaters more portable than records, say if you were writing a library
>(.so or .dll, etc.)?
> Can a c++ or c program deal with a pascal record?
> How about speed and performance?
>
>  
>
I think the best way is to pass the record as a var parameter, e. g.:

type t_my_record = record
  a: integer;
  b: string;
  c: boolean;
end;

procedure my_procedure(var a_record: t_my_record);

In this case, a simple pointer is passed to my_procedure. This is also 
the way most C libraries work, passing a pointer to a structure.

When a function returns a record, an additional pointer parameter is 
passed to it, invisibly to the pascal programmer, and the function fills 
in the structure pointed to by that parameter.

For this reason, I personally tend to prefer a var-parameter: A function 
returning a record looks like creating or allocating that record, which 
is not true. A  var-parameter shows, in pascal, a structure similar to 
what happens on the machine code level. But it's a matter of taste, and, 
of how the function result is used: When the result is often used as 
part of expressions, or as a parameter to other procedures, the "result" 
way is more legible than the "var-parameter" way.

Anton.






More information about the fpc-pascal mailing list