2

I'd like to do something like this:

procedure show(a : Array of Integer);
var
  i : integer;
begin
  for i in a do
    writeln(i);
end;
begin
  show((1, 2));
  show((3, 2, 5));
end.

but this is the closest I got

Program arrayParameter(output);
type
  TMyArray = Array[0..2] of Integer;
var
  arr : TMyArray = (1, 2, 3);
procedure show(a : TMyArray);
var
  i : integer;
begin
  for i in a do
    writeln(i);
end;
begin
  show(arr);
end.

So do I have to declare a different array for each time I want to call the function? Please provide a working example.

1
  • Arrays always imply [] - don't mix that up with initializing a variable with (), which is unbound to the type. Commented Apr 4, 2020 at 15:57

1 Answer 1

4

If you do

procedure show(a: array of Integer);
var
  i: Integer;
begin
  for i in a do
    Writeln(i);
end;

then you may write

show([1, 2, 3, 4]);

This kind of array parameter is called an open array parameter. If a function has an open array parameter, you can give it both dynamic and static arrays, in addition to these "literal arrays". So, given our show procedure, we may also do

var
  DynArr: TArray<Integer>; // = array of Integer
  StaticArr: array[0..2] of Integer;

begin
  show(DynArr);
  show(StaticArr);
end;

Just for comparison: If you instead do

procedure show(a: TArray<Integer>);

or has a

type
  TDynIntArray = array of Integer;

and do

procedure show(a: TDynIntArray);

then show will only accept such dynamic arrays.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.