I realise that one should not expect true Boolean
s to become 1
when cast to an Integer
, purely that they become non-0
.
However, the result changes depending on whether the variable is a Variant
(but varBoolean
) or a Boolean
.
Consider the following:
I := Integer(true);
I
is now 1
.
But...
var
I: Integer;
V: Variant;
begin
V := true;
I := Integer(V);
end;
I
is now -1
.
Of course, if I cast V to a Boolean
before casting the resulting Boolean
to an Integer
, I
becomes -1
.
But I am curious as to why that is.
Is this because of the way that Boolean
s are stored (say as 1
bits), and when casting to an Integer
, Delphi performs a conversion, which does not occur when casting a Variant
to Integer
?
I only bring this up, because if you are used to a true Boolean
casting to 1
, it can be dangerous to have varBoolean
share case with varInteger
in a VarType()
-case
.
For instance:
case VarType(V) of
varInteger, varBoolean: I := Integer(V);
end;
Would not behave as one might expect.
A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.
Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.
In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.
Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0. The following table shows comparisons and boolean operations.
The behaviour is indeed as expected. The varBoolean
type corresponds to VT_BOOL
. Which is documented like this:
VT_BOOL
A Boolean value. True is -1 and false is 0.
You also say that Delphi's boolean is stored as 1 bit. That's not actually true. They are stored in a single byte, 8 bits. I suppose the key point is that a VT_BOOL
variant does not contain a Delphi Boolean
. The VT_BOOL
variant is a different beast altogether, dating originally from VB. Raymond Chen discusses this a little here: BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With