The four
predefined Boolean types are Boolean, ByteBool, WordBool,
and LongBool. Boolean is the preferred type. The others exist to
provide compatibility with other languages and operating system libraries.
A Boolean
variable occupies one byte of memory, a ByteBool variable also occupies
one byte, a WordBool variable occupies two bytes (one word), and a LongBool
variable occupies four bytes (two words).
Boolean values are denoted by the predefined constants True and False. The following relationships hold.
|
Boolean |
ByteBool, WordBool, LongBool |
|
False <
True |
False
<> True |
|
Ord(False) = 0 |
Ord(False) = 0 |
|
Ord(True) = 1 |
Ord(True) <> 0 |
|
Succ(False) = True |
Succ(False) = True |
|
Pred(True) = False |
Pred(False) = True |
A value
of type ByteBool, LongBool, or WordBool is considered True
when its ordinality is nonzero. If such a value appears in a context where a Boolean
is expected, the compiler automatically converts any value of nonzero
ordinality to True.
The
remarks above refer to the ordinality of Boolean values not to the values
themselves. In Object Pascal, Boolean expressions cannot be equated with
integers or reals. Hence, if X is an integer variable, the statement
if
X then ...;
generates a compilation error. Casting the variable to a Boolean type is unreliable, but each of the following alternatives will work.
if
X <> 0 then ...; {
use longer expression that returns Boolean value }
var
OK: Boolean {
use Boolean variable }
...
if
X <> 0 then OK := True;
if
OK then ...;
Object
Pascal中提供了4个预定义布尔类型:Boolean、ByteBool、WordBool、LongBool。其中,Boolean是首选类型,其他布尔类型是为了向其他语言和操作系统提供兼容。
Boolean变量占用一个字节的内存,ByteBool变量也占用一个字节,WordBool变量占用两个字节(一个字),LongBool变量占用四个字节(双字)。
布尔值用预定义常量True和False表示。下面是各种布尔类型中值的关系:
|
Boolean |
ByteBool, WordBool, LongBool |
|
False <
True |
False
<> True |
|
Ord(False) = 0 |
Ord(False) = 0 |
|
Ord(True) = 1 |
Ord(True) <> 0 |
|
Succ(False) = True |
Succ(False) = True |
|
Pred(True) = False |
Pred(False) = True |
对于ByteBool、LongBool、WordBool类型,当值的序号非零时,值被认为是True。如果这样的一个值出现在需要Boolean类型的上下文中,编译器将自动将所有序号非零的值转换成True。
上面的说明是指布尔值的序号而不是指布尔值。在Object Pascal中,布尔表达式不能被等同为整数或实数。因此,如果 X 是一个整数类型的变量,那么语句
if
X then ...;
将产生一个编译错误。转换变量到布尔类型是不可靠的,但可以通过下面的语句来达到相同的目的:
if
X <> 0 then ...; {
使用长的表达式返回布尔值 }
var
OK: Boolean {
使用布尔变量 }
...
if
X <> 0 then OK := True;
if
OK then ...;