Why can't I use SetLength in a function that receives an array parameter?

I am trying to use the following function to set the length of a dynamic array, which is a var parameter. Error trying to compile code:

[dcc64 error] lolcode.dpr (138): E2008 Incompatible types

function execute(var command : array of string) : Boolean; begin // Do something SetLength(command,0); end; 
+7
source share
2 answers

Define Type

 type TStringArray = array of string; 

and you can do

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

You suffer from a general and fundamental misunderstanding of array parameters. What are you here for:

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

not really a dynamic array . This 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 change the length of a dynamic array. You can only change its elements.

If you need to change the length of a dynamic array, the procedure should get a dynamic array. There is an idiomatic way to write in modern Delphi:

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

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

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

How can you choose whether to use the parameters of an open array or dynamic array? In my opinion, you should always use open arrays, if possible. And if this is not possible, use dynamic arrays as the final object. 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 an array with a constant size as a parameter of an open array, but not if the function receives a dynamic array.

+14
source

All Articles