- Pascal 教程
- Pascal - 首页
- Pascal - 概述
- Pascal - 环境设置
- Pascal - 程序结构
- Pascal - 基本语法
- Pascal - 数据类型
- Pascal - 变量类型
- Pascal - 常量
- Pascal - 运算符
- Pascal - 决策制定
- Pascal - 循环
- Pascal - 函数
- Pascal - 过程
- Pascal - 变量作用域
- Pascal - 字符串
- Pascal - 布尔值
- Pascal - 数组
- Pascal - 指针
- Pascal - 记录
- Pascal - 变体
- Pascal - 集合
- Pascal - 文件处理
- Pascal - 内存
- Pascal - 单元
- Pascal - 日期和时间
- Pascal - 对象
- Pascal - 类
- Pascal 有用资源
- Pascal - 快速指南
- Pascal - 有用资源
- Pascal - 讨论
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 的目录中运行它。