Typed constants, unlike true
constants, can hold values of array, record, procedural, and pointer types.
Typed constants cannot occur in constant expressions.
In the default {$J-}
compiler state, typed constants can not have new values assigned to them; they
are, in effect, read-only variables. However, if the {$J+} compiler
directive is in effect, typed constants can have new values assigned to them;
they behave essentially like initialized variables.
Declare a typed constant like
this:
const identifier: type
= value
where identifier is any valid
identifier, type is any type except files and variants, and value
is an expression of type type. For example,
const Max:
Integer = 100;
In most cases, value must be a constant expression; but if type is an array, record, procedural, or pointer type, special rules apply.
类型常量不同于真实常量,它能保存数组、记录、程序型以及指针类型的值。类型常量不能出现在常量表达式中。
在缺省的编译状态 {$J-} 中,类型常量不能被赋予新的值,这时的类型常量相当于只读变量。然而,如果编译指示 {$J+} 有效,那么类型常量可以被赋予新的值,这时的类型常量相当于被初始化过的变量。
可以如下声明类型常量:
const identifier: type
= value
这里的是identifier一个有效标识符,type是除文件和变体外的任意类型,value是类型type的常量表达式。例如,
const Max:
Integer = 100;
大多数情况下,value必需是一个常量表达式;但如果类型type是一个数组、记录、程序型或指针类型,那么它们各自适用于特别的规则。
编者注
编译指示 {$J-} 和 {$J+} 是局部的。也就是说,对于不同的类型常量,可以分别设置其是否只读。例如:
{$J+}
const
Hello: string = 'Hello';//Hello相当于初始化了的变量
{$J-}
Max: Integer = 100;//Max相当于只读变量
...
Hello := 'HELLO';//合法:可以赋予新值
Max := 200;//非法:不能赋予新值