Break
Deutsch · English · Español · Français · Suomi · Русский
The break (pseudo) routine effectively destroys a loop. Its primary application is to exit a loop prior its planned end.
Break, with its special meaning of abandoning a loop, 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 identifier system.break at any time, though.
Collatz conjecture
Example: The following program tackles the Collatz problem. The for-loop in collatzIterative uses a break, a) to check for the terminating condition according to Collatz’ problem, b) to abort prior reaching the data type’s boundaries, and c) while still using the advantage of the for-construct (i. e. automatically incrementing a variable within a specified range).
program collatz(input, output, stderr);
procedure collatzIterative(n: qword);
var
i: qword;
begin
for i := 0 to high(i) do
begin
writeLn('step ', i:20, ': ', n);
// Collatz conjecture: sequence ends with 1
if (n = 1) or (n > (high(n) / 3 - 1)) then
begin
// leave loop, as next value may get out of range
break;
end;
// n := ifThen(odd(n), 3 * n + 1, n div 2);
if odd(n) then
// n is odd
begin
n := 3 * n + 1;
end
// n is even
else
begin
n := n div 2;
end;
end;
end;
var
n: longword;
begin
readLn(n);
if n < 1 then
begin
writeLn(stderr, 'not a positive integer');
halt(1);
end;
collatzIterative(n);
end.Choosing a for-loop in conjunction with a break is adequate, since the Collatz conjecture hypothesizes that the described function eventually ends in 1, but does not tell for sure. Therefore – mathematically speaking – writing while n <> 1 do does not consider the circumstance, that the problem is an assumption, but would suggest it was determined to eventually result in n = 1.
Other remarks
However, 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 body contains a break to determine all abort conditions.
According to the GPC manual, break is a Borland Pascal extension, whereas Mac Pascal has leave. FPC, apart from {$mode MacPas}, only knows break, though.
See also
breakin thesystemunit- exit to return from routines
- continue to skip the rest of an iteration
- goto
sources
1
compare remarks in the reference manual § “The For..to/downto..do statement” and § “reserved words”
From the Free Pascal wiki, page "Break", as it stood on 2020-11-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.