Why does true boolean value become -1 when converted to integer?
I understand that one cannot expect true to Boolean
become 1
when cast to Integer
, only that they become not 0
.
However, the result changes depending on whether the variable is Variant
(but varBoolean
) or Boolean
.
Consider the following:
I := Integer(true);
I
now 1
.
But...
var
I: Integer;
V: Variant;
begin
V := true;
I := Integer(V);
end;
I
now -1
.
Of course, if I pass V to Boolean
before it gets Boolean
to Integer
, it I
becomes -1
.
But I'm curious as to why this is so.
Is it because of what is stored Boolean
(for example, as 1
bits), and when transferred to Integer
Delphi does a conversion that does not occur when casting Variant
to Integer
?
I only use this because if you are used to a true Boolean
application 1
it can be dangerous to have a varBoolean
shared resource with varInteger
in VarType()
- case
.
For example:
case VarType(V) of
varInteger, varBoolean: I := Integer(V);
end;
Will not behave the way you would expect.
source to share
The behavior is indeed as expected. The type varBoolean
matches VT_BOOL
. Which is documented as follows:
VT_BOOL
Boolean value. True is -1 and false is 0.
You also say that Delphi boolean is stored as 1 bit. This is actually not the case. They are stored in one byte, 8 bits. The key point, I suppose, is that the variant VT_BOOL
does not contain Delphi Boolean
. Variant VT_BOOL
is a very different beast originally created from VB. Raymond Chen discusses a bit here: BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool .
source to share
This is an old thread, but I thought I'd add a slight inconsistency in that the SysUtils.BoolToStr () function by default returns "-1" as true and "0" as false.
And to confuse things a little more, SysUtils.StrToBool () returns true if the string is any number (even floating point), not 0.
source to share