Break

From Free Pascal wiki
Revision as of 02:43, 14 February 2018 by Kai Burghardt (talk | contribs) (add more explanation)
Jump to navigationJump to search

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 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, 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		writeLn('step ', i:20, ': ', n);
 9		
10		// Collatz conjecture: sequence ends with 1
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		// n := ifThen(n mod 2 = 0, n div 2, 3 * n + 1);
18		if n mod 2 = 0 then
19		// n is even
20		begin
21			n := n div 2;
22		end
23		// n is odd
24		else
25		begin
26			n := 3 * n + 1;
27		end;
28	end;
29end;
30
31var
32	n: longword;
33begin
34	readLn(n);
35	
36	if n < 1 then
37	begin
38		writeLn(stderr, 'not a positive integer');
39		halt(1);
40	end;
41	
42	collatzIterative(n);
43end.

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

  • break in the system unit
  • exit to return from routines
  • continue to skip the rest of an iteration

sources

1
compare remarks in the reference manual § “The For..to/downto..do statement” and § “reserved words”