Goto Statements

A goto statement, which has the form goto label transfers program execution to the statement marked by the specified label. To mark a statement, you must first declare the label. Then precede the statement you want to mark with the label and a colon:

label: statement

Declare labels like this:

label label;

You can declare several labels at once: label label1, ..., labeln;

A label can be any valid identifier or any numeral between 0 and 9999.

The label declaration, marked statement, and goto statement must belong to the same block. (See Blocks and Scope, below.) Hence it is not possible to jump into or out of a procedure or function. Do not mark more than one statement in a block with the same label.

For example, label StartHere;

StartHere: Beep; goto StartHere;

creates an infinite loop that calls the Beep procedure repeatedly.

Additionally, it is not possible to jump into or out of a try-finally or try-except statement.

The goto statement is generally discouraged in structured programming. It is, however, sometimes used as a way of exiting from nested loops, as in the following example.

procedure FindFirstAnswer;

var X, Y, Z, Count: Integer; label FoundAnAnswer; begin

Count := SomeConstant; for X := 1 to Count do for Y := 1 to Count do for Z := 1 to Count do if ... { some condition holds on X, Y, and Z } then goto FoundAnAnswer;

... { Code to execute if no answer is found } Exit;

FoundAnAnswer:

end;

Notice that we are using goto to jump out of a nested loop. Never jump into a loop or other structured statement, since this can have unpredictable effects.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment