Delphi coding hints and tips.
Using Break and Continue in loops
Break.
Use break to terminate, break out of an enclosing for, while or repeat looping early.
var
I:Integer;
Index:Integer;
Ints:array[1..100]of Integer;
begin
for Index:=Low(Ints) to High(Ints) do
begin
if Ints[Index]=I then
begin
ShowMessage('Index of '+IntToStr(I)+'='+IntToStr(Index));
Break;
end;
end;
end;
The above example shows a loop scaning sequencally a array of integers for the first number I. Once its found I it then displays here it is in the array. Now we have found I there is no need for any more iterations so we can break out of loop thus saving much processing.
Note that break will respect any try finally statments. If break is called from within a try part of a try finally enclosed by loop the finally will be entered.
Continue.
Use Continue to force an enclosing for, while or repeat loop into its next iteration skipping the remains of the current iteration.
for Index:=0 to ListBox1.Items.Count-1 do
begin
{Check file name selected in list box.}
if not(ListBox1.Selected[Index]) then Continue;
{Check file exists.}
if not(FileExists(ListBox1.Items[Index])) then Continue;
{Process file...}
end;
The above example shows a loop scaning a list box which contains a list of file names. For each file in the list it firsts checks if it is selected and then that the file exists. If a check fails it just continues to the next file in the list.
Note that continue will respect any try finally statments. If continue is called from within a try part of a try finally enclosed by loop the finally will be entered.}.


