I noticed the other day on StackOverflow somebody mentioned that if you need to use Break in For loop, to use While instead of For.

I noticed the other day on StackOverflow somebody mentioned that if you need to use Break in For loop, to use While instead of For.
I use a lot of For loops with Break, so today I tried to use While instead of For and it doesn't really make sense to me.

For example:

I have simple array of records that are organized as header (level = 0), detail (level = 1):

TRec = record
Level: integer;// header, detail
Processed: boolean;
end;

DataArray: TArray; // array with multiple header, details records

and if I need to process all details of a specific header I do it like this:

ProcessDetails(DataArray, 10); // Example of processing details of Header at index 10 in DataArray..

// method with For loop
procedure ProcessDetails(var aArray: TArray; aHeaderIndex: integer);
var i: integer;
begin
// Process all details of selected Header

// details are listed after Header
for i := aHeaderIndex + 1 to High(aArray) do
begin
if aArray[i].Level = 0 then
Break; // End on next Header

aArray[i].Processed := True;
end;
end;

And then I setup same example with While:

// method with While loop
procedure ProcessDetails(var aArray: TArray; aHeaderIndex: integer);
var i: integer;
begin
// Process all details of selected Header
if aArray = nil then
Exit; // stop if no data

i := aHeaderIndex + 1; // details are listed after Header
while aArray[i] > 0 do
begin
aArray[i].Processed := True;
Inc(i);
end;
end;

It seems For loop more readable and I don't need checking if array is empty at the beginning.

Also adding additional conditions when For loop should Break would be better readable then adding the additional condition to While loop.

Any thoughts on this, am I missing something with While that makes sense to use it over For loop in such cases?

Comments

  1. Gerhard Venter I would not use break there, but exit.

    ReplyDelete
  2. Gerhard Venter

    for Client in Clients.Values do
    if Client.FClientId = pClientId then
    Exit(Client);

    Result := nil;

    or even

    for Result in Clients.Values do
    if Result.FClientId = pClientId then
    Exit;

    Result := nil;

    or

    Result := Clients.Values.FirstOrDefault(HasClientId(pClientId));

    ;)

    ReplyDelete
  3. Stefan Glienke Thank you, I like that!

    ReplyDelete

Post a Comment