[fpc-pascal] Dynamic array as return type of functions

Tom Verhoeff T.Verhoeff at tue.nl
Wed May 23 14:05:14 CEST 2007


On Wed, May 23, 2007 at 11:36:20AM +0300, Christos Chryssochoidis wrote:
> 
> >>It *is* allowed. The only trick is that you have to declare a type for
> >>your dynamic array, i.e. you have to write something like
> 
> Yes, I have noticed that if you first wrap a dynamic array in a type  
> definition then you can declare a function returning such an array,  
> but it seemed to me as an unnecessary complication of things and as  
> an inconsistency in the language. However, the distinction between  
> dynamic and open arrays that D.Mantione says, explains this  
> complication.

It is not a trick, but has to do with type compatibility issues
(and history, I guess).

If you have 

function f(...): SomeType;

then the result of calling f needs to go somewhere.  Either it
"disappears" as an intermediate result in a larger expression, or you
assign it to a variable (or such).  In case it is a subexpression,
the result of f acts as a parameter of an enclosing function or operator.

  while f(...) operator ... do ...

  if g( f(...) ) then ...

  v := f(...)

The receiving parameter or variable needs to have a type "compatible"
with SomeType.  If SomeType is a type expression, then you cannot declare
a parameter or variable of the same type by copying the type expression.
In Pascal,

var
  a: array [ Char ] of Integer;
  b: array [ Char ] of Integer;

function g(p: array [ Char ] of Integer);
function f(c: Char; i: Integer): array [ Char ] of Integer;

does not (automatically) make a and b have the same type (in some
cases automatic conversions etc. will give you some kind of compatibility).

For that (partly historic) reason, parameter types and return types must
be type names and not type expressions.

Of course, there situations where you can argue that it works without
using type names.  E.g. if you return a record type, one way of using
it would be to select a field:

function f(...): record x, y: Integer end;

  if f(...).x = 0 then ...

The "operation" of field selection works on arbitrary record types.
Insisting on a type name seems unneeded.  I.e. the typing of
the "parameters" of . is not so strict; it occurs in a context

  record . fieldname_of_this_record_type

The record is not a parameter of . in the usual sense.

I haven't checked the FPC documentation on all this.

	Tom
-- 
E-MAIL: T.Verhoeff @ TUE.NL     | Dept. of Math. & Comp. Science
PHONE:  +31 40 247 41 25        | Technische Universiteit Eindhoven
FAX:    +31 40 247 54 04        | PO Box 513, NL-5600 MB Eindhoven
http://www.win.tue.nl/~wstomv/  | The Netherlands



More information about the fpc-pascal mailing list