Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does true variant booleans become -1 when cast to an integer?

Tags:

delphi

I realise that one should not expect true Booleans 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 Booleans 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.

like image 367
Svip Avatar asked Aug 05 '15 09:08

Svip


People also ask

Is boolean true or false or 1 or 0?

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.

Is true equal to 1 in Python?

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.

How do you change true/false to 1 0 in Python?

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.

Is 1 boolean true?

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.


1 Answers

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.

like image 162
David Heffernan Avatar answered Sep 20 '22 03:09

David Heffernan