Break
│
Deutsch (de) │
English (en) │
español (es) │
suomi (fi) │
français (fr) │
русский (ru) │
The break
routine effectively destroys a loop.
Its primary application is to exit a loop prior its planned end.
break
can only be written within loops.
It is not a reserved word¹, therefore you could shadow it, but access it by writing the fully qualified identfier system.break
at any time, though.
Example:
The following program considers the Collatz problem.
The for
-loop in collatzIterative
uses a break
, a) to abort prior reaching the data type's boundaries, and b) while still using the advantage of the for
-construct, that is condition-checking and automatically incrementing a variable.
0program collatz(input, output, stderr);
1
2procedure collatzIterative(n: qword);
3var
4 i: qword;
5begin
6 for i := 0 to high(i) do
7 begin
8 // #9 is a tab character
9 writeLn(i, #9, n);
10
11 if (n = 1) or (n > (high(n) / 3 - 1)) then
12 begin
13 // leave loop, as next value may get out of range
14 break;
15 end;
16
17 if n mod 2 = 0 then
18 // n is even
19 begin
20 n := n div 2;
21 end
22 // n is odd
23 else
24 begin
25 n := 3 * n + 1;
26 end;
27 end;
28end;
29
30var
31 n: longword;
32begin
33 readLn(n);
34
35 if n < 1 then
36 begin
37 writeLn(stderr, 'not a positive integer');
38 halt(1);
39 end;
40
41 collatzIterative(n);
42end.
The usage of break
is usually considered as bad style, since it “delegitimizes” the loop's condition expression.
You have to know a loop's statement block contains a break
to determine all abort conditions.
According to the GPC manual, break
is a Borland Pascal extension, whereas Mac Pascal has leave
.
see also
sources
- 1
- compare remarks in the reference manual § “The
For..to
/downto..do
statement” and § “reserved words”