The basic syntax for a variable
declaration is
var identifierList: type;
where identifierList is a
comma-delimited list of valid identifiers and type is any valid type.
For example,
var I:
Integer;
declares a variable I of type Integer,
while
var X, Y:
Real;
declares two variables X and Y of type Real.
Consecutive variable declarations
do not have to repeat the reserved word var:
var
X, Y, Z: Double;
I, J, K: Integer;
Digit: 0..9;
Okay: Boolean;
Variables declared within a
procedure or function are sometimes called local, while other variables
are called global. Global variables can be initialized at the same time
they are declared, using the syntax
var identifier: type
= constantExpression;
where constantExpression is any constant expression representing a value
of type type. Thus the declaration
var I:
Integer = 7;
is equivalent to the declaration and
statement
var I:
Integer;
...
I := 7;
Multiple variable declarations
(such as var X, Y, Z: Real;) cannot include initializations, nor can declarations
of variant and file-type variables.
If you don’t explicitly initialize
a global variable, the compiler initializes it to 0. Local variables, in
contrast, cannot be initialized in their declarations and contain random data
until a value is assigned to them.
When you declare a variable, you
are allocating memory which is freed automatically when the variable is no
longer used. In particular, local variables exist only until the program exits
from the function or procedure in which they are declared. For more information
about variables and memory management, see Memory management.
变量声明的基本语法是
var identifierList: type;
这里的identifierList是一个逗号分割的有效标识符列表,type是一个任意的有效类型。例如,
var I:
Integer;
声明了一个类型为Integer的变量I,类似地
var X, Y:
Real;
声明了类型为Real的两个变量X和Y。
连续的变量声明不必重复使用保留字var:
var
X, Y, Z: Double;
I, J, K: Integer;
Digit: 0..9;
Okay: Boolean;
声明在过程或函数内部的变量有时叫做局部的(local),而其他变量叫做全局的(global)。全局变量可以在声明的同时用下列语法对其进行初始化
var identifier: type
= constantExpression;
这里的constantExpression是任何表示类型为type的值的常量表达式。因此,如下声明
var I:
Integer = 7;
等价于如下声明和语句
var I:
Integer;
...
I := 7;
多重变量声明(如var X, Y, Z:
Real;)不能包括初始化,也不能包括变体和文件类型变量的声明。
如果没有明确地初始化全局变量,那么编译器将对其初始化为0。不同的是,局部变量不能在其声明中被初始化并且在其被赋值之前包含的是随机数据。
声明变量时的同时,也为其自动分配内存,并且,当不再使用时自动释放其内存。特别是局部变量,当程序的执行点进入到定义该局部变量的函数或过程时一直存在,直到程序从量的函数或过程中退出。有关变量和内存管理的更多信息,见内存管理。