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.
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.