当前位置: 首页 > 文档资料 > Pascal 中文教程 >

goto statement

优质
小牛编辑
110浏览
2023-12-01

Pascal中的goto语句提供从goto到同一函数中的带标签语句的无条件跳转。

NOTE - 在任何编程语言中都不鼓励使用goto语句,因为它很难跟踪程序的控制流程,使程序难以理解且难以修改。 任何使用goto的程序都可以被重写,因此它不需要goto。

语法 (Syntax)

Pascal中goto语句的语法如下 -

goto label;
   ...
   ...
label: statement;

这里, label必须是无符号整数标签,其值可以是1到9999。

流程图 (Flow Diagram)

Pascal goto声明

例子 (Example)

以下程序说明了这个概念。

program exGoto;
label 1; 
var
   a : integer;
begin
   a := 10;
   (* repeat until loop execution *)
   1: repeat
      if( a = 15) then
      begin
         (* skip the iteration *)
         a := a + 1;
         goto 1;
      end;
      writeln('value of a: ', a);
      a:= a +1;
   until a = 20;
end.

编译并执行上述代码时,会产生以下结果 -

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

请注意 -

  • 在Pascal中,必须在常量和变量声明之前声明所有标签。

  • 可以在复合语句中使用ifgoto语句将控制转移出复合语句,但将控制转移到复合语句中是非法的。