Pascal - goto 語句



Pascal 中的 goto 語句提供從 goto 到同一函式中帶標籤的語句的無條件跳轉。

注意 - 強烈建議在任何程式語言中都不要使用 goto 語句,因為它使程式控制流的跟蹤變得困難,從而使程式難以理解和難以修改。任何使用 goto 的程式都可以重新編寫,這樣它就不需要 goto。

語法

Pascal 中 goto 語句的語法如下 -

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

此處,標籤必須是無符號整數標籤,其值可以是 1 至 9999。

流程圖

Pascal goto statement

示例

以下程式說明了這個概念。

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 語句將控制權從複合語句中轉移出去,但將控制權轉移到複合語句中是非法的。

pascal_loops.htm
廣告
© . All rights reserved.