首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 布林類型完解:Boolean、ByteBool、WordBool、LongBool 差異與陷阱

     編輯:Delphi

四種布林類型對照

類型大小順序性Ord(False)Ord(True)用途
Boolean1 Byte有序01首選,標準邏輯
ByteBool1 Byte無序0<>0 (通常 1)C/C++ 相容
WordBool2 Bytes無序0<>016-bit API 相容
LongBool4 Bytes無序0<>0 (常為 -1)32-bit API/Windows 相容

關鍵差異:有序 vs 無序

  • Boolean:False < True,Succ(False)=True,Pred(True)=False。可用於陣列索引、集合運算。
  • 其他三種:False <> True 但 無順序關係,Succ(False)=True、Pred(True)=False 但 Pred(False)=True (循環)。不可 作為陣列索引或集合元素。

檔案儲存陷阱

type
  ByteBoolFile = file of ByteBool;
  LongBoolFile = file of LongBool;

procedure CompareSize;
var BF: ByteBoolFile; LF: LongBoolFile; B: Boolean;
begin
  B := False;
  AssignFile(BF, 'test1.bin'); Rewrite(BF); Write(BF, B, B, B, B); CloseFile(BF);  // 4 bytes
  AssignFile(LF, 'test2.bin'); Rewrite(LF); Write(LF, B, B, B, B); CloseFile(LF);  // 16 bytes
end;

同樣 4 個 False,檔案大小分別為 4 與 16 位元組。混用型別讀寫同一檔案會導致資料錯位。

Ord(True) 陷阱

var B: Boolean; LB: LongBool;
begin
  B := True; LB := True;
  ShowMessage(IntToStr(Ord(B)));   // 永遠顯示 1
  ShowMessage(IntToStr(Ord(LB)));  // 可能顯示 -1 (視編譯器/平台)
end;

切勿假設 Ord(True) = 1 適用於所有布林類型,與 Windows API 交互時務必用 LongBool 對應 BOOL。

最佳實務

  1. 純 Pascal 邏輯一律用 Boolean。
  2. 呼叫 Windows API (BOOL 參數/回傳) 使用 LongBool 或直接用 LongBool 變數接收。
  3. 與 C/C++ DLL 交互依對方定義選 ByteBool/WordBool/LongBool。
  4. 序列化/檔案儲存統一轉換為 Byte (0/1) 或明確指定型別,避免跨平台/版本差異。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved