Break

From Lazarus wiki
Revision as of 12:18, 8 March 2018 by Djzepi (talk | contribs)
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, 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 identfier 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).

 1program collatz(input, output, stderr);
 2
 3procedure collatzIterative(n: qword);
 4var
 5	i: qword;
 6        // i: integer;
 7begin
 8	for i := 0 to high(i) do
 9	begin
10		writeLn('step ', i:20, ': ', n);
11		
12		// Collatz conjecture: sequence ends with 1
13		if (n = 1) or (n > (high(n) / 3 - 1)) then
14		begin
15			// leave loop, as next value may get out of range
16			break;
17		end;
18		
19		// n := ifThen(n mod 2 = 0, n div 2, 3 * n + 1);
20		if odd(n) then
21		// n is odd
22		begin
23                        n := 3 * n + 1;
24			
25		end
26		// n is even
27		else
28		begin
29			n := n div 2;
30		end;
31	end;
32end;
33
34var
35	n: longword;
36begin
37	readLn(n);
38	
39	if n < 1 then
40	begin
41		writeLn(stderr, 'not a positive integer');
42		halt(1);
43	end;
44	
45	collatzIterative(n);
46end.

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 is 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 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. FPC only knows break, though.

See also

sources

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