Cardinal Type
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.
// 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;