views:

82

answers:

3

In VB6, coercing True to an integer yields the value -1.

Why is this so? What is the reasoning behind this?

In most other programming languages (C/C++, Java, Perl, Python, etc.), true becomes 1 when coerced into an integer. In boolean algebra, the value 1 is used to represent true/on. Why does VB6 do it differently?

I do see a certain elegant symmetry in the fact that a bitwise-not of -1 (True) will yield 0 (False), and vice-versa (because of -1's representation being all 1s in two's complement), but I can't think of any practical benefits of this identity.

I'm only asking out of curiosity, by the way -- this was something that struck me as odd when I first learnt VB6, and I've been wondering ever since.

+2  A: 

True is represented as only binary ones (11111111 etc..), false as only zeros (00000 etc..)

The datatype int is signed, that means the msb when zero tells us that the value is positive, and when one that it's negative. Try to overflow the largest, possible, positive number by one, it will then "roll over" to the largest, negative number possible.

Decimal -1 is represented as only ones. There you have it :)

Onkelborg
+2  A: 

This is been true in Microsoft basic for a long time, GW-BASIC at least. I think it's because there was no actual boolean type in those days or a separate logical NOT operator, so to make the integer NOT operator work with both true and false, they used values 0 and -1. Positive 1 wouldn't have worked because NOT 1 is not zero.

Chris Smith
+4  A: 

You came very close to the reason... Eric Lippert reveals the horrible, horrible truth:

What's going on is that VBScript is not logical. VBScript is bitwise. All the so-called logical operators work on numbers, not on Boolean values! Not, And, Or, XOr, Eqv and Imp all convert their arguments to four-byte integers, do the logical operation on each pair of bits in the integers, and return the result. If True is -1 and False is 0 then everything works out, because -1 has all its bits turned on and 0 has all its bits turned off.

(As Chris Smith notes, this has been true of various flavors of BASIC for a long time...)

Note that in VB.NET, logical operators (that is, operators that operate only on Boolean datatypes) were introduced, but the existing operators will still happily perform bitwise operations if fed integral types. This has been a frequent source of frustration for me when moving between C++ and VB...

Shog9
I know :) I don't like VB ;)
Onkelborg
Interesting! Thanks for the link. I knew that the logical operators did not short circuit and worked bitwise for integers, but I didn't realise they were _only_ bitwise, even for Boolean values. And @Onkelborg, I don't like VB either, I was just curious as to this anomaly ;-)
Cameron
Good :) Ther's hope for mankind :)
Onkelborg