Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal
communitycreator
array
parameters

What are open array parameters in Pascal?

Kainat Asif

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;  
begin  
  Temp := arr[0];  
  For I := 1 to High(arr) do 
    Temp := Temp + arr[I];  
  Sum := Temp;  
end;

Var  
  arr : Array [1..6] of integer;
  arr2 : Array [1..10] of integer;
  I : integer;
begin
  For I := 1 to 6 do 
    arr[I] := I;
  Writeln('Sum of elements of arr = ',Sum(arr));
  
  For I := 1 to 10 do 
    arr2[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 Sum function.
    • The Sum function takes arr as an open array parameter. This means that the size of arr is not declared in the definition of Sum.
  • Line 20: We pass an array arr of size 6 to the Sum function as an open array parameter.
  • Line 24: We pass an array arr2 of size 10 to the Sum function as an open array parameter.

RELATED TAGS

pascal
communitycreator
array
parameters
RELATED COURSES

View all Courses

Keep Exploring