# Lazarus

## Free Pascal => General => Topic started by: riwu on December 26, 2015, 07:50:00 am

Title: break/continue nested loop
Post by: riwu on December 26, 2015, 07:50:00 am
Are there constructs in FPC to break/continue multi/nested loops?
Or are using flags/labels the only way?
Code: Pascal  [Select][+][-]
1.
2.   for i:=0 to 10 do
3.   begin
4.     for j:=0 to 10 do
5.     begin
6.       if someCondition then
7.         break(2); //break out of both loops, go to methodC
8.
9.       if someCondition2 then
10.         continue(2); //break out if j loop and skip methodB
11.
12.       methodA();
13.     end;
14.
15.     methodB();
16.   end;
17.
18.   methodC();
Title: Re: break/continue nested loop
Post by: eny on December 26, 2015, 09:23:06 am
YAGNI (https://en.m.wikipedia.org/wiki/You_aren%27t_gonna_need_it)
Title: Re: break/continue nested loop
Post by: GetMem on December 26, 2015, 09:29:16 am
Quote
@riwu
Are there constructs in FPC to break/continue multi/nested loops?
No.

Quote
@riwu
Or are using flags/labels the only way?
Never do that! Break down the lops to procedures/functions instead:
Code: Pascal  [Select][+][-]
1. function LoopJ: Integer;
2. var
3.   J: integer;
4. begin
5.   Result := -1; //default, no special attention needed
6.   for J := 0 to 10 do
7.   begin
8.     if SomeCondition1 then
9.     begin
10.       Result := 0;
11.       Exit; //break out of both loops, go to methodC
12.     end;
13.
14.     if SomeCondition2 then
15.     begin
16.       Result := 1;
17.       Exit; //break out j loop and skip methodB
18.     end;
19.     MethodA;
20.   end;
21. end;
22.
23. procedure LoopI;
24. var
25.   I, Res: Integer;
26. begin
27.   for I := 0 to 10 do
28.   begin
29.     Res := LoopJ;
30.     case Res of
31.       0: Exit;
32.       1: Continue;
33.     end;
34.     MethodB;
35.     //you can add other stuff here
36.   end;
37. end;
38.
39. procedure TForm1.Button1Click(Sender: TObject);
40. begin
41.   LoopI;
42.   MethodC
43. end;
44.
Title: Re: break/continue nested loop
Post by: guest58172 on December 26, 2015, 11:40:24 am
YAGNI (https://en.m.vvikipedia.org/wiki/You_aren%27t_gona_need_it)

Some languages features look superfluous but when you need them you're happy to have them.
Title: Re: break/continue nested loop
Post by: eny on December 26, 2015, 01:43:28 pm
Some languages features look superfluous but when you need them you're happy to have them.
We're not talking about 'some superfluous language features' but about a specific (albeit theoritical and contrived and therefore rather superfluous) question from TS.
Getmem already answered more comprehensively the direction TS needs to lean towards.