vb6language-design

Why is -1 the result of coercing True to an integer in VB6?


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.


Solution

  • 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...