Maru
Maru

Reputation: 942

Why can I not use SetLength in a function which receives an array parameter?

I am trying to use the following function to set the length of a dynamic array which is a var param. There is only an error when I try to compile the code:

[dcc64 Error] lolcode.dpr(138): E2008 Incompatible Types

function execute(var command : array of string) : Boolean;
begin
  // Do something
  SetLength(command,0);
end;

Upvotes: 10

Views: 6922

Answers (2)

David Heffernan
David Heffernan

Reputation: 613013

You are suffering from a common and fundamental mis-understanding of array parameters. What you have here:

function execute(var command: array of string): Boolean;

is not in fact a dynamic array. It is an open array parameter.

Now, you can pass a dynamic array as a parameter to a function that receives an open array. But you cannot modify the length of the dynamic array. You can only modify its elements.

If you need to modify the length of the dynamic array, the procedure must receive a dynamic array. In modern Delphi the idiomatic way to write that is:

function execute(var command: TArray<string>): Boolean;

If you are using an older version of Delphi that does not support generic arrays then you need to declare a type for the parameter:

type
  TStringArray = array of string;
....
function execute(var command: TStringArray): Boolean;

How should you choose whether to use open array or dynamic array parameters? In my opinion you should always use open arrays if possible to do so. And if not possible, then use dynamic arrays as a final resort. The reason being a function with an open array parameter is more general than one with a dynamic array parameter. For example, you can pass a constant sized array as an open array parameter, but not if the function receives a dynamic array.

Upvotes: 18

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

Define a type

type
  TStringArray = array of string;

and you can do

function Execute(var StringArray: TStringArray): boolean;
begin
  // Do something
  SetLength(StringArray, 0);
end;

Upvotes: 10

Related Questions