aleroot
aleroot

Reputation: 72636

Dynamic Array as optional parameter in Delphi 7

Is it possible to pass to a function or procedure a dynamic array as optional parameter ? If yes, how ?

I have tried in this way :

procedure testp (str : string; var arr : StringArray = nil);
begin
    str := 'Ciao Alessio !';
    SetLength(arr, 2);
    arr[0] := 'Ale';
    arr[1] := 'Ale';
end;

but it gives : default parameter 'arr' must be by-value or const .

I'm using Delphi 7, but if not possible with Delphi 7, is it possible with newer version of Delphi or Free Pascal ?

Upvotes: 1

Views: 3878

Answers (2)

Rob Kennedy
Rob Kennedy

Reputation: 163277

The error message means exactly what it says, and it has nothing to do with the parameter being a dynamic array. The compiler would have rejected that code no matter what type the parameter had because you're not allowed to give default values for parameters passed by reference.

To make an optional reference parameter, use overloading to give two versions of the function. Change your current function to receive its parameter by value or const, as the compiler advises, and then declare another function without that parameter, as follows:

procedure testp (str : string);
var
  arr: StringArray;
begin
  testp(str, arr);
end;

That is, declare a dummy parameter and pass it to the "real" function. Then simply throw away the value it returns.

If calculation of the reference value is expensive, then the implementation of the one-parameter version of testp will instead duplicate more of the code from the two-argument version.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612954

Default parameters can only be specified for const or by value parameters. They cannot be specified for var parameters.

To achieve the caller flexibility you are looking for you'll need to use overloads.

procedure foo(var arr: StringArray); overload;
begin
  .... do stuff
end;

procedure foo; overload;
var
  arr: StringArray;
begin
  foo(arr);
end;

Upvotes: 5

Related Questions