Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: Goto not considered harmful in this case?

Tags:

goto

delphi

Alright, so you have a TObjectList instance. You want to loop through the items in it and delete some of the objects from the list. You can't do this:

for I := 0 to ObjectList.Count - 1 do
  if TMyClass(ObjectList[I]).ShouldRemove then
    ObjectList.Delete(I);

...because once you delete the first object the index counter I will be all wrong and the loop won't work any more.

So here is my solution:

Again:
  for I := 0 to ObjectList.Count - 1 do
    if TMyClass(ObjectList[I]).ShouldRemove then
    begin
      ObjectList.Delete(I);
      goto Again;
    end;

This is the best solution I've found to this so far. If anyone has a neater solution I'd love to see it.

like image 468
David Avatar asked Nov 28 '22 01:11

David


2 Answers

Try this instead:

 for I := ObjectList.Count - 1 downto 0 do
   if TMyClass(ObjectList[I]).ShouldRemove then
     ObjectList.Delete(I);

That looks like a particularly bad use of goto, jumping out of the for loop like that. I assume it works (since you're using it), but it would give me the willies.

like image 139
Larry Lustig Avatar answered Dec 20 '22 05:12

Larry Lustig


You can also use

  I := 0;
  while I < ObjectList.Count do begin
    if TMyClass(ObjectList[I]).ShouldRemove then ObjectList.Delete(I)
    else Inc(I);
  end;
like image 45
kludg Avatar answered Dec 20 '22 04:12

kludg