Que Clng, Clng.
July 27, 2007 12:32 PM   Subscribe

In VBScript, why is Clng(True) equal to -1?

I am looking for preferably some current or ex-Microsoftie who might be able to give me the real deal on why this decision was made internally or otherwise, some sane, valid reasoning would do nicely. In all that is logical, it would really seem that Clng(True) should equal 1. Especially since Clng(False) is equal to 0. My brain asplode.
posted by zackola to Technology (5 answers total) 1 user marked this as a favorite
 
Same reason Microsoft does everything else it does:

I have heard it was for backwards compatibility with antediluvian versions of BASIC that Gates himself wrote.
posted by mrbugsentry at 12:40 PM on July 27, 2007


Best answer: Because the bitwise negation of zero is -1 in two's complement. It's not a good reason, but it's the reason.
posted by gmarceau at 12:47 PM on July 27, 2007


Best answer: gmarceau has the answer. To be more specific, it's so that Visual Basic doesn't have to distinguish between bitwise and logical operators, like many other languages have to.

-1 | 0 = -1 (true).
-1 & 0 = 0 (false).
!0 = -1 (in 2's complement).
!-1 = 0.

This wouldn't work if you defined true to be 1.
posted by zixyer at 1:21 PM on July 27, 2007


Best answer: Simple answer: Because that's the way it is in VB, and VBScript is designed to be maximally compatible with VB.

Complicated answer: The root of this is that in VB Script and pre-.Net VB, there was only one and operator. In C-derived languages you have & for bitwise and and && for logical and. Combine this with a fairly weak type system and -1 is the only logical value for True to have.

You obviously want any non-zero value to act as if it were True in the context of a boolean operation. Consider the expression "6 And (1 > 0)". If True had the value 1, the bitwise result of the operation would be (110 & 001) == 0, which would be False. By using -1 (all 1's in binary, as noted above), you can be assured that [any non-zero value] And [any expression evaluating to true] results in [some other non-zero value].

Given the constraints, there were two choices: Make True == 1, or make non-zero values act as True in boolean operations. The latter is far more useful to the average programmer.

In modern version of Visual Basic, the weird CLng(True) behavior remains, but stronger typing and the AndAlso operator make this generally moot.

I do work on the Visual Basic team, but this decision was made a long, long time before I even started middle school.
posted by 0xFCAF at 1:30 PM on July 27, 2007 [2 favorites]


Just use the absolute value, it'll work the way you want.
posted by blue_beetle at 3:49 PM on July 27, 2007


« Older Should I be worrying my pretty little head over...   |   Parking and Photography at Berkeley's Greek... Newer »
This thread is closed to new comments.