Site Tools


VBScript is not Logical

Developer: RhinoScript
Summary: Discusses the logic, or lack of, in VBScript.

Question

Consider the following statements:

If blnResult = True Then Print "True!" Else Print "False!"

and

If blnResult Then Print "True!" Else Print "False!"

Is there a difference?

Answer

Yes, there is a big difference. If blnResult is True or False, then both statements do what you would expect – the same thing. But, the first statement is asking “Is blnResult equal to True?” whereas the second question is asking “Is blnResult not equal to False?”

More Information

In a strictly Boolean world, those are equivalent statements. But the VBScript type system is richer than just Booleans.

For example, what if blnResult is the string “True”? The string “True” is not equal to the Boolean True, so the first statement is false. But the string is also not equal to False, so the second statement is true, and therefore the statements have different semantics.

The same goes for numbers. When converted to a number, True converts to -1 (for reasons which will become clear in a moment) and False converts to 0. Therefore, if blnResult is 1, again the first statement is false because 1 <> -1, and the second statement is true because 1 <> 0.

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. But if other numbers get in there, all bets are off.

This can lead to some strange situations if you're not careful. In VBScript, it is certainly possible for

If blnResult Then

and

If blnAnswer Then

to be both true, but

If Blah And Foo Then

to be false, if blnResult is 1 and blnAnswer is 2, for example.

Best Practices

Conditional statements should always take Booleans. Or, in other words, use Booleans as Booleans, use nothing else as Booleans.

Suppose you've got a method that returns a number and you want to do something if it doesn't return zero. Don't do this, even though it does exactly what you want:

If intResult Then

it's clearer to call it out and make the conditional take a Boolean:

If intResult <> 0 Then

Conversely, if a value is a Boolean and you know that, there's no need to compare it. When I see

If blnResult = True Then

If blnResult can only contain True or False, then you can just say

If Blah Then

Use the same practice with logical operators. Do not mix-n-match - either every argument should explicitly be a number, and you're doing bitwise comparisons, or every argument is a Boolean. Mixing the two makes the code harder to read and more bug-prone.

developer/scriptsamples/vbslogic.txt · Last modified: 2014/06/26 (external edit)