Open Array Parameters

Open array parameters allow arrays of different sizes to be passed to the same procedure or function. To define a routine with an open array parameter, use the syntax array of type (rather than array [x..y] of type) in the parameter declaration. For example, function Find(A: array of Char): Integer;

declares a function called Find that takes a character array of any size and returns an integer.

Note: The syntax of open array parameters resembles that of dynamic array types, but they do not mean the same thing. The previous example creates a function that takes any array of Char elements, including (but not limited to) dynamic arrays. To declare parameters that must be dynamic arrays, you need to specify a type identifier:

type TDynamicCharArray = array of Char; function Find(A: TDynamicCharArray): Integer;

Within the body of a routine, open array parameters are governed by the following rules.

  • They are always zero-based. The first element is 0, the second element is 1, and so forth. The standard Low and High functions return 0 and Length1, respectively. The SizeOf function returns the size of the actual array passed to the routine.
  • They can be accessed by element only. Assignments to an entire open array parameter are not allowed.
  • They can be passed to other procedures and functions only as open array parameters or untyped var parameters. They cannot be passed to SetLength.
  • Instead of an array, you can pass a variable of the open array parameter's base type. It will be treated as an array of length 1.

When you pass an array as an open array value parameter, the compiler creates a local copy of the array within the routine's stack frame. Be careful not to overflow the stack by passing large arrays.

The following examples use open array parameters to define a Clear procedure that assigns zero to each element in an array of reals and a Sum function that computes the sum of the elements in an array of reals.

procedure Clear(var A: array of Real); var

I: Integer; begin for I := 0 to High(A) do A[I] := 0; end;

function Sum(const A: array of Real): Real; var

for I := 0 to High(A) do S := S + A[I]; Sum := S; end;

When you call routines that use open array parameters, you can pass open array constructors to them.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment