Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBS logical operators initialise empty variables?

Tags:

vbscript

Consider the following bit of VBS:

dim msg, myVar, myVar2

msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)

msgbox msg, , "BEFORE"

if not myVar then myVar2 = true

msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)

msgbox msg, , "AFTER"

I would expect the output from "BEFORE" and "AFTER" to be the same... all we're doing is making a comparison to an uninitialised (empty) variant right?

However - it seems like the "if not" actually initialises it to a (long)zero! I've been coding in VBS (ASP) for donkey's years, and this is a new one on me!

A few things to note:

  • The behaviour is the same in both a .vbs and the equivalent ASP code (on my Win 7 desktop and on Server 2008 R2.)
  • All logical operators - and/or/not/xor produce this effect
  • Comparison operators do not.

It seems like a potential trap for the unwary... Can anyone explain this behaviour?

like image 334
beercohol Avatar asked Apr 28 '15 16:04

beercohol


People also ask

Is null or empty VBScript?

In VBScript—where all variables are variants—variables can be one of two special values: EMPTY or NULL. EMPTY is defined as a variable with an un-initialized value, whereas NULL is a variable that contains no valid data.

How do you declare variables in VBScript?

Declaring Variables Variables are declared using “dim” keyword. Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration. Example 1 − In this Example, IntValue can be used as a String, Integer or even arrays.

Is empty in VBScript?

The IsEmpty function returns a Boolean value that indicates whether a specified variable has been initialized or not. It returns true if the variable is uninitialized; otherwise, it returns False.

How do you declare a boolean variable in VBScript?

You can set the Boolean data type to either True or False, which are represented by -1 and 0, respectively, in VBScript. This subtype is useful when working with variables where you want to determine or set a condition.


1 Answers

I couldn't find anything official about this issue. After doing some test, I decided that this is a bug or an un-documented effect. This behaviour does not apply on other similar platforms like VBA and VB6.

Visual Basic for Application:

Visual Basic for Application

Visual Basic 6:

Visual Basic 6

VBScript:

VBScript

As a workaround, passing expressions by value works.

If Not (exp) Then
'or
If Not CBool(exp) Then

ByRef and ByVal Parameters
CBool Function

like image 83
Kul-Tigin Avatar answered Feb 01 '23 04:02

Kul-Tigin