In addition to David's and Mason's superb answers, I would like to share my personal Exit
usage favorite. Let's call it, quite contrary to "safe guard", a "last resort provider". ;)
The basic idea:
function Search(List: TList; Item: TObject): Integer;
begin
for Result := 0 to List.Count - 1 do
if List[Result] = Item then
Exit;
Result := -1;
end;
Other more realistic examples (from this answer and this answer):
const
Order: array[0..6] of String = ('B', 'C', 'A', 'D', 'G', 'F', 'E');
function GetStringOrder(const S: String; CaseSensitive: Boolean): Integer;
begin
for Result := 0 to Length(Order) - 1 do
if (CaseSensitive and (CompareStr(Order[Result], S) = 0)) or
(not CaseSensitive and (CompareText(Order[Result], S) = 0)) then
Exit;
Result := Length(Order);
end;
function FindControlAtPos(Window: TWinControl; const ScreenPos: TPoint): TControl;
var
I: Integer;
C: TControl;
begin
for I := Window.ControlCount - 1 downto 0 do
begin
C := Window.Controls[I];
if C.Visible and PtInRect(C.ClientRect, C.ScreenToClient(ScreenPos)) then
begin
if C is TWinControl then
Result := FindControlAtPos(TWinControl(C), ScreenPos)
else
Result := C;
Exit;
end;
end;
Result := Window;
end;
And concluding with a quote from Delphi's help on the compiler error message FOR-Loop variable '<element>' may be undefined after loop:
You can only rely on the final value of a for loop control variable if the loop is left with a goto or exit statement.