Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dynamic array is empty

Tags:

arrays

delphi

I have a procedure declared like so:

procedure MyProc(List: Array of string);

I want to know how to check if the List parameter is empty.

For example:

procedure MyProc(List: Array of string);
begin
  if List=[] then // here I want to check if the List array is empty
  //do something
  else 
  //do something else
end;

How I can do this?

like image 848
DelphiNewbie Avatar asked Apr 28 '11 05:04

DelphiNewbie


3 Answers

you can use the Length function

procedure MyProc(List: Array of string);
begin
  if Length(List)=0 then // is empty ?
  //do something
  else 
  // do something else
end;
like image 62
RRUZ Avatar answered Sep 28 '22 07:09

RRUZ


Empty arrays are equal to nil:

if List = nil then // it's empty

(That also means SetLength(List, 0) and List := nil are equivalent commands.)

Empty arrays have a last index that's less than the first index, which for the open array in your example means having a negative last index:

if High(List) < 0 then // it's empty

That means that if you want to avoid running a loop on an empty array, you don't have to do anything special. Just write the loop as you normally would:

for i := Low(List) to High(List) do // won't run if List is empty
like image 22
Rob Kennedy Avatar answered Sep 28 '22 05:09

Rob Kennedy


Personally I always write

if Assigned(List) then

rather than

if List<>nil then

because I believe it reads better, and not just for dynamic arrays.


That answers the question for dynamic arrays, but your example is an open array, so there are two possible questions here.

For open arrays I would use Length() or high() to take decision based on the size of the array. I would not be seduced by arguments that Pointer(List)<>nil is quicker than Length(List)<>nil. The difference in speed between these options will not be discernible and so you should use the most clear and readable option.

like image 24
David Heffernan Avatar answered Sep 28 '22 07:09

David Heffernan