Pascal - 程式結構



在學習 Pascal 程式語言的基本構建塊之前,讓我們先看看一個最簡單的 Pascal 程式結構,以便在接下來的章節中將其作為參考。

Pascal 程式結構

Pascal 程式基本上包含以下部分:

  • 程式名稱
  • Uses 命令
  • 型別宣告
  • 常量宣告
  • 變數宣告
  • 函式宣告
  • 過程宣告
  • 主程式塊
  • 每個塊中的語句和表示式
  • 註釋

每個 Pascal 程式通常都有一個標題語句、一個宣告部分和一個執行部分,並且嚴格按照這個順序排列。以下格式顯示了 Pascal 程式的基本語法:

program {name of the program}
uses {comma delimited names of libraries you use}
const {global constant declaration block}
var {global variable declaration block}

function {function declarations, if any}
{ local variables }
begin
...
end;

procedure { procedure declarations, if any}
{ local variables }
begin
...
end;

begin { main program block starts}
...
end. { the end of main program block }

Pascal Hello World 示例

以下是一個簡單的 Pascal 程式碼,它將列印“Hello, World!”:

program HelloWorld;
uses crt;

(* Here the main program block starts *)
begin
   writeln('Hello, World!');
   readkey;
end. 

這將產生以下結果:

Hello, World!

讓我們看看上面程式的各個部分:

  • 程式的第一行 program HelloWorld; 指示程式的名稱。

  • 程式的第二行 uses crt; 是一個預處理器命令,它告訴編譯器在進行實際編譯之前包含 crt 單元。

  • 接下來在 begin 和 end 語句之間包含的程式碼行是主程式塊。Pascal 中的每個塊都包含在一個 begin 語句和一個 end 語句之間。但是,指示主程式結束的 end 語句後面跟著一個句點(.),而不是分號(;)。

  • 主程式塊的 begin 語句是程式執行開始的地方。

  • (*...*) 之間的程式碼行將被編譯器忽略,它被用來在程式中新增註釋

  • 語句 writeln('Hello, World!'); 使用 Pascal 中可用的 writeln 函式,該函式導致訊息“Hello, World!” 顯示在螢幕上。

  • 語句 readkey; 允許顯示暫停,直到使用者按下某個鍵。它是 crt 單元的一部分。單元就像 Pascal 中的庫。

  • 最後一個語句 end. 結束你的程式。

編譯和執行 Pascal 程式

  • 開啟一個文字編輯器並新增上述程式碼。

  • 將檔案儲存為 hello.pas

  • 開啟命令提示符並轉到儲存檔案的目錄。

  • 在命令提示符下鍵入 fpc hello.pas 並按 Enter 鍵編譯程式碼。

  • 如果程式碼中沒有錯誤,命令提示符將帶你到下一行,並將生成hello 可執行檔案和hello.o 物件檔案。

  • 現在,在命令提示符下鍵入hello 執行程式。

  • 你將能夠看到“Hello World”列印在螢幕上,並且程式會等待你按下任何鍵。

$ fpc hello.pas
Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64
Copyright (c) 1993-2011 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling hello.pas
Linking hello
8 lines compiled, 0.1 sec

$ ./hello
Hello, World!

確保 free pascal 編譯器fpc 在你的路徑中,並且你正在包含原始檔 hello.pas 的目錄中執行它。

廣告