Description
Goto statements unconditionally transfer program execution to the statement prefixed by a label. Execution of a goto statement is terminated when it transfers program execution. If a goto statement transfers program execution to a statement outside of the current block then the call stack is unwound (i.e. functions and procedure calls are terminated) until the block containing the statement referred to by the goto statement is reached. So for example if the main program calls a procedure A, and procedure A calls procedure B, and procedure B calls procedure C, and a goto statement in procedure C transfers program execution back to a statement in procedure A then procedures C and B are terminated.
Standard Pascal (ISO/IEC 7185) describes the rules governing the use of goto statement as follows:
A label, if any, of a statement S shall be designated as prefixing S. The label shall be permitted to occur in a goto-statement G if and only if any of the following three conditions is satisfied.
a) S contains G.
b) S is a statement of a statement-sequence containing G.
c) S is a statement of the statement-sequence of the compound-statement
of the statement-part of a block containing G.
To fully understand these rules you will probably need a copy of the Standard (ISO/IEC 7185) but the following explanation should suffice for most people.
The first two rules cover goto statements that refer to statements in the current block, while the last rule covers goto statements that refer to statements in an enclosing block. The rules are basically saying that you can't use a goto statement to jump into the middle of a statement from outside of that statement. So for example the following code fragment is illegal.
goto 1;
for i := 1 to 10 do
1: writeln(i)
Example
Below is a simple program illustrating how to use goto statements.
program ten(output);
label loop;
var
count : integer;
begin
count := 1;
loop: writeln(count);
count := count + 1;
if count <= 10 then goto loop
end.
NOTE: The label loop used in this program is declared before it is used (which is a requirement for all labels).
Syntax
(NOTE: for clarity some parts of the syntax are omitted, see Irie Pascal Grammar for the full syntax):
goto-statement = 'goto' label