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?
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;
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With