Name

Cardinal Type

Syntax

type Cardinal = 0..4294967295;

Description

The Cardinal type is an unsigned integer subrange whose size is the natural size of an integer. In Delphi 5, the size is 32 bits, but in future versions of Delphi, it might be larger. Use LongWord for an unsigned integer type that must be 32 bits, regardless of the natural size of an integer. See the Integer type for information about other integer types.

Tips and Tricks

  • The most common use for Cardinal is calling Windows API or other external functions that take parameters of type DWORD (unsigned long in C or C++).

  • If you need an integer type for natural or whole numbers, you should usually define your own subranges, as shown here:

// Better than Cardinal for use in computation
type
  Whole = 1..MaxInt;
  Natural = 0..MaxInt;
  • Using Cardinal as an ordinary integer type often gives results different from what you expect because the result might be any Integer or Cardinal value. The range of values covered by each individual type is 32 bits, but the combination requires 33 bits. Thus, any arithmetic operation that combines Integer and Cardinal values forces the compiler to expand the operands to at least 33 bits—so Delphi converts the operands to the Int64 type:

type
  I: Integer;
  C: Cardinal;
begin
  ReadLn(I, C);
  // Result of I+C can be Low(Integer)..High(Cardinal), which
  // requires 33 bits, so Delphi must use Int64 for the result type.
  WriteLn(I + C);

  // Comparing Integer and Cardinal requires changing I and C to
  // Int64 in order to compare the numbers correctly. For example,
  // consider what happens when I=Low(Integer) and C=High(Cardinal),
  // and you try to compare the values as 32-bit integers.
  if I < C then
    WriteLn('I < C'),
end;

See Also

Int64 Type, Integer Type, LongWord Type
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset