Break: Difference between revisions

From Free Pascal wiki
Jump to navigationJump to search
(add more explanation)
m (highlighting shift)
Line 12: Line 12:


<!-- leave the ifThen expanded, for those who aren't quite familiar with the math unit -->
<!-- leave the ifThen expanded, for those who aren't quite familiar with the math unit -->
<syntaxhighlight lang="pascal" line start="0" highlight="14">
<syntaxhighlight lang="pascal" line start="0" highlight="15">
program collatz(input, output, stderr);
program collatz(input, output, stderr);



Revision as of 02:45, 14 February 2018

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.

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(n mod 2 = 0, n div 2, 3 * n + 1);
		if n mod 2 = 0 then
		// n is even
		begin
			n := n div 2;
		end
		// n is odd
		else
		begin
			n := 3 * n + 1;
		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.

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”