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

 1program exitDemo(input, output, stdErr);
 2var
 3	i: integer;
 4begin
 5	readLn(i);
 6	if i = 0 then
 7	begin
 8		exit;
 9	end;
10	writeLn(123 div i);
11end.

is effectively identical to

 1program exitDemo(input, output, stdErr);
 2label
 3	9999;
 4var
 5	i: integer;
 6begin
 7	readLn(i);
 8	if i = 0 then
 9	begin
10		goto 9999;
11	end;
12	writeLn(123 div i);
139999:
14end.

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.

 3function ackermann(const m, n: ALUUInt): ALUUInt;
 4begin
 5	if m = 0 then
 6	begin
 7		exit(n + 1);
 8	end;
 9	if n = 0 then
10	begin
11		exit(ackermann(m - 1, 1));
12	end;
13	exit(ackermann(m - 1, ackermann(m, n - 1)));
14end;

In this example the line

7		exit(n + 1);

is equivalent to

7		ackermann := n + 1;
8		exit;

exceptions

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

 1program tryExitDemo(input, output, stdErr);
 2{$modeSwitch exceptions+}
 3begin
 4	try
 5		exit;
 6		writeLn('Try.');
 7	finally
 8		writeLn('Finally.');
 9	end;
10	writeLn('Bye.');
11end.

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