When you declare a pointer
constant, you must initialize it to a value that can be resolved at least as a
relative address at compile time. There are three ways to do this: with the @
operator, with nil, and (if the constant is of type PChar) with a
string literal. For example, if I is a global variable of type Integer,
you can declare a constant like
const PI:
^Integer = @I;
The compiler can resolve this
because global variables are part of the code segment. So are functions and
global constants:
const PF:
Pointer = @MyFunction;
Because string literals are
allocated as global constants, you can initialize a PChar constant with
a string literal:
const
WarningStr: PChar = 'Warning!';
Addresses of local (stack-allocated) and dynamic (heap-allocated) variables cannot be assigned to pointer constants.
声明指针常量时,必需将其初始化为一个至少在编译时就能确定相对地址的值。可以有三种途径实现:用地址运算符@,用空指针nil,以及用串文本(如果指针的类型是PChar)。例如,如果 I 是一个类型为Integer的全局变量,那么可以如下声明一个常量
const PI:
^Integer = @I;
编译器能确定该常量的值,因为全局变量是代码段的一部分。函数和全局常量也如此:
const PF:
Pointer = @MyFunction;
因为串文本作为全局常量分配,所以可以用其对PChar类型的常量进行初始化:
const
WarningStr: PChar = 'Warning!';
局部地址(栈分配)和动态地址(堆分配)的变量不能赋给指针常量。