What are open array parameters in Pascal?
Overview
Open array parameters are arrays passed as parameters with an unspecified length.
Note: To get the length (or last index) of open array parameters inside a function or a procedure, we can use the
High()function.
Return value
If an empty array (array with size 0) is passed as an open array parameter, the high() function returns -1.
Parameters
Open array parameters can be passed by reference, value, or constant parameters.
Example
The code snippet below demonstrates the use of an open array parameter:
{$MODE DELPHI}Function Sum (arr : Array of integer) : integer;Var I : longint;Temp : integer;beginTemp := arr[0];For I := 1 to High(arr) doTemp := Temp + arr[I];Sum := Temp;end;Vararr : Array [1..6] of integer;arr2 : Array [1..10] of integer;I : integer;beginFor I := 1 to 6 doarr[I] := I;Writeln('Sum of elements of arr = ',Sum(arr));For I := 1 to 10 doarr2[I] := I;Writeln('Sum of elements of arr = ',Sum(arr2));end.
Output
Sum of elements of arr = 21
Sum of elements of arr = 55
Code explanation
- Line 3: We declare a
Sumfunction.- The
Sumfunction takesarras an open array parameter. This means that the size ofarris not declared in the definition ofSum.
- The
- Line 20: We pass an array
arrof size 6 to theSumfunction as an open array parameter. - Line 24: We pass an array
arr2of size 10 to theSumfunction as an open array parameter.