当前位置:首页 > 软件开发 > dev
firefox

Delphi中布尔类型辨析

delphi中预定义的布尔类型有四种:boolean ,bytebool,wordbool,longbool。其中,boolean 类型是首选布尔类型,其余三种是为其它编程语言和windows 环境提供兼容性支持。这些布尔类型在使用上大同小异,但如果混淆使用将可能会有意外结果。

  现做简单辨析供大家参考。

  

一、从资源占用的角度进行比较
  一项boolean 类型的数据占用 1字节的内存;

  一项bytebool类型的数据占用 1字节的内存;

  一项wordbool类型的数据占用 2字节的内存;

  一项longbool类型的数据占用 4字节的内存。

  如果开发者在进行程序设计时将构造一种含有布尔数据类型的结构类型,那么在资源占用方面将有所考虑。尽管这些数据类型之间是可以相互赋值的,但某些特殊情况下是有区别的。首先看下面的语句:

  type

   byteboolfile = file of bytebool;

   longboolfile = file of longbool;

  这里,如果在这两中类型文件中存储相同数量的布尔值,其文件大小是不同的。而对同一物理文件按照这两种类型文件分别读取数据,其结果更是相去甚远。

  下面是比较bytebool和longbool的一段程序,得到的文件 test1.bin和 test2.bin的文件尺寸分别为 4字节和16字节。

  procedure comparebyteboolwithlongbool;

  const

   fname1 = c: est1.bin;

   fname2 = c: est2.bin;

  type

   byteboolfile = file of bytebool;

   longboolfile = file of longbool;

  var

   bf: byteboolfile;

   lf: longboolfile;

   b: boolean;

  begin

   b := false;

   assignfile(bf, fname1);

   rewrite(bf);

   write(bf, b, b, b, b);

   closefile(bf);

   assignfile(lf, fname2);

   rewrite(lf);

   write(lf, b, b, b, b);

   closefile(lf);

  end;

  有兴趣的朋友可以在此基础上再比较一下读取数据的区别,你会有更奇特的发现。

二、从布尔值的操作角度进行比较
  在delphi中,布尔值只能被赋予预定义的常量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

  不难看出,boolean 类型的有序的,而其它三种布尔数据类型是无序的。下面的程序给出了其中的部分区别:

  procedure comparebooleanwithlongbool;

  var

   b: boolean;

   lb: longbool;

  begin

   b := false;

   lb := false;

   if ord(b) = ord(lb) then

    showmessage(ord(b) = ord(lb) [b = lb = false]) //将被执行

   else

    showmessage(ord(b) <> ord(lb) [b = lb = false]);

   b := true;

   lb := true;

   if ord(b) = ord(lb) then

    showmessage(ord(b) = ord(lb) [b = lb = true])

   else

    showmessage(ord(b) <> ord(lb) [b = lb = true]); //将被执行

   showmessage(ord(b) = + inttostr(ord(b)));     //一定是 1

   showmessage(ord(lb) = + inttostr(ord(lb)));    //可能是-1

  end;

 ↓相关文章:
© 2006-2008 All Rights Reserved