22 Votes

Delphi/Lazarus: Go through Array independent from Index

Question by Guest | Last update on 2024-01-23 | Created on 2014-09-28

I would like to loop through a complete array in Delphi/Lazarus independent from its start and its end index.

Up to now, I have always used something like i:=0 to length(array)-1, but I have also some arrays that are not starting at an index of 0.

So, is there any possibility to simplify the task to begin or start the loop at an arbitrary index (and not 0 in each case)? For example some function to retrieve or determine the smallest index of a given array?

ReplyPositiveNegative
2Best Answer2 Votes

Just use low(arrary) and high(array) instead of 0 and length(array). With low(), you get the first index of the array, with high() you get the last.

The "-1" which you need when you use length(array) is not necessary with this since you directly receive the last index of the array.

var
  array_dyn: array of integer;
  array_stat: array[2..7] of integer;
begin
  SetLength(array_dyn, 5);

  for i := low(array_dyn) to high(array_dyn) do begin
     // corresponds to i := 0 to 4
     array_dyn[i] := 1;
  end;

  for i := low(array_stat) to high(array_stat) do begin
     // corresponds to i := 2 to 7
     array_stat[i] := 1;
  end;

end;

As you can see in this example, you can use low() and high() with static as well as with dynamic arrays.
2014-09-28 at 14:28

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.