Exit

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) English (en)

The pseudo-procedure exit immediately leaves the surrounding block. It is similar to C’s return.

behavior

Exit is an UCSD Pascal extension. As of FPC version 3.2.0 it is available in all compiler compatibility modes.

basic

Invoking exit has the same effect as a goto to an invisible label right before the block’s end. The program

program exitDemo(input, output, stdErr);
var
	i: integer;
begin
	readLn(i);
	if i = 0 then
	begin
		exit;
	end;
	writeLn(123 div i);
end.

is effectively identical to

program exitDemo(input, output, stdErr);
label
	9999;
var
	i: integer;
begin
	readLn(i);
	if i = 0 then
	begin
		goto 9999;
	end;
	writeLn(123 div i);
9999:
end.

Confer the respective assembly language output. In a manner of speaking, using exit merely avoids the “taboo word” goto.

functions

Inside a function definition exit optionally accepts one argument. This argument must be assignment-compatible to and defines the functions result before actually transferring control to the function’s call site.

function ackermann(const m, n: ALUUInt): ALUUInt;
begin
	if m = 0 then
	begin
		exit(n + 1);
	end;
	if n = 0 then
	begin
		exit(ackermann(m - 1, 1));
	end;
	exit(ackermann(m - 1, ackermann(m, n - 1)));
end;

In this example the line

		exit(n + 1);

is equivalent to

		ackermann := n + 1;
		exit;

exceptions

Any accompanying finally frame is executed before actually jumping to the block’s end. Consider the following example:

program tryExitDemo(input, output, stdErr);
{$modeSwitch exceptions+}
begin
	try
		exit;
		writeLn('Try.');
	finally
		writeLn('Finally.');
	end;
	writeLn('Bye.');
end.

This program outputs one line:

Finally.
Light bulb  Note: Exit may not appear in a finally frame.

notes

  • Exit is a regular identifier. You can redefine it. You can refer to its special meaning via the FQI (fully-qualified identifier) system.exit at any time. NB: Exit is compiler intrinsic and not actually defined in the system unit.
  • Exit can be implemented as an unconditional jmp instruction. In higher optimization levels it might get eliminated.
  • The FPC does not support naming the block to leave like the GNU Pascal Compiler does. FPC’s implementation will always leave the closest containing block. GPC’s implementation allows to leave any surrounding block by supplying the respective routine’s name as an argument.

see also