David'sとMasonの素晴らしい回答に加えて、Exit
が好きな使い方を分かちたいと思います。それを「セーフガード」、「最後のリゾートの提供者」とは全く反対にしましょう。 ;)
基本的な考え方:
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;
他のより現実的な例(this answerとthis answerから):Delphiのヘルプからの引用で
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;
と結論コンパイラのエラーメッセージFOR-Loop vaループはgoto文または終了文で残っている場合にのみ、ループの制御変数の最終値に依存することができます
:riable「> <要素」がループ後不定になることがあります。
この質問は、議論と推測を求めるので、ここでは本当に適切ではありません。より適切な場所ではなく、[プログラマー](http://programmers.stackexchange.com)に属しています。 [FAQ](http://stackoverflow.com/faq)は、このタイプの質問を、このサイトの形式とデザインにはあまり適していないと具体的に言及しています。プログラマーに移行する投票。 –
私はあなたに次の記事を勧めますhttp://programmers.stackexchange.com/questions/77530/best-practices-concerning-exit-in-delphiこれは、詳細な方法で同じ件名をカバーしています。 – RBA
リンクされたサイトは、誤解と品質の低い情報でよく知られています。それを無視します。彼がうまくいっていないのは、*単一出口点*の概念です。 – OnTheFly