What side-effects arise from setting a Long variable equal to False? - vb6

I am working on a piece of legacy code at work and I ran into a variable assignment that raises some questions for me. The variable PortOpen was declared with its type set as Long, and later in the code it was set equal to False. Since the integer value of False is 0, I assume that this will just mean the PortOpen will be 0 until it is modified, but I am suspicious that this might introduce some subtle bugs. A Long is twice the size of a Boolean in this case, so is there any possibility for an error when later using PortOpen in a logic comparison? Or, just in general, are there any quirks or other effects of using this type of variable assignment?

This is of course a bad thing as it is confusing for a person reading the code, but as long as you use 0/False for the false values and -1/True for true values the program should work fine.
You need to watch out for using 1 for True, as that will give you ambigous results. 1 (or in fact any value other than 0) will give you True in logical comparisons, so this will display "True":
Dim myvar As Long
myvar = 2
If myvar Then
MsgBox "True"
Else
MsgBox "False"
End If
However, the problem arises when you apply a "Not" to this expression. Generally you would expect "Not True" to be "False", but the following code will display "True":
Dim myvar As Long
myvar = 2
If Not myvar Then
MsgBox "True"
Else
MsgBox "False"
End If
So, apart from being bad for readability of your code, using Integer or Long for booleans CAN lead to errors in your code.

As you say PortOpen will be 0 after the automatic conversion of True to a Long, there are no other side effects of this assignment.
Aside from being bad practice & confusing for others the only other potential problem would be any assumption that PortOpen = 1 = True which is not the case as Clng(True) is -1.
Personally I would replace the assignemtnet with 0 or a 0 CLOSED symbolic constant/enum.

Related

Assigning to multiple variables fails for even number of variables [duplicate]

Working with legacy code I came across some strange variable assignments that I am not sure are legal VB6 syntax, but I cannot find the documentation to back up the feeling.
Dim ComStart, ComEnd, CR As Boolean
ComStart = ComEnd = CR = False
My suspicions are
a) the original declarations should be
Dim ComStart as Boolean, ComEnd as Boolean, CR as Boolean
b) the declarations as they are implemented now will not assign anything to ComStart.
Any answers or documentation are much appreciated
The code you have found is technically legal VB6, because it compiles and runs. But it is very likely that the original author thought the code would do something different! There are two misunderstandings.
ComStart and ComEnd and CR are variants, not Booleans.
In VB6 = is the equality operator, not the assignment operator found in C.
CR = False does not change the value of CR. It compares the current value of CR to False, and evaluates as True if CR is equal to False. Let's say it evaluates as False
Now you have the expression ComEnd = False. Again, this does not change the value of ComEnd. It compares it with False, and evaluates as True if ComEnd is equal to False. This time let's say it evaluates as True.
Now you have the assignment statement ComStart = True. This sets the value of ComStart to True
So your original code
Dim ComStart, ComEnd, CR As Boolean
ComStart = ComEnd = CR = False
Creates two variants ComStart and ComEnd and a Boolean CR, and then
CR keeps its default value, False
ComEnd keeps its default value, Empty
ComStart is set to False because Empty = (Empty = False) is False.
Simple! ... I hope the rest of the legacy code is less, well, accidental.
So the code should be, as you guessed:
Dim ComStart as Boolean, ComEnd as Boolean, CR as Boolean
That's a common mistake on VB6 developers with little or no experience, or .NET developers working on VB6 code :). It works, because VB6 would assume the value assigned and would cast it automatically, but it can also cause nasty bugs really hard to debug.

Integer and String comparison conflict in VBScript

The below VBScript code while trying to run in HP-UFT confused me because the first statement prints True instead of False (which does not seem logical), while the second one prints False (which seems logical)
Code:
print 40 = "40"
a = 40
b = "40"
print a = b
Output:
True
False
It's perfectly logical (cough), there is only one data type in VBScript and that is Variant. However VBScript can handle many different sub types of the Variant data type.
When you compare
40 = "40"
VBScript is implicitly converting the String sub type to an Integer sub type and comparing the result which is the same as performing the following explicit conversion;
40 = CInt("40")
If you already have your variants defined however VBScript only attempts to implicitly convert them if the execution context fits (when it fits is a bit hazy and in some cases a straight up bug - See Ref).
To avoid this use explicit conversions when necessary.
a = CInt(b)
Useful Links
A: VBScript implicit conversion in IF statement different from variable to literals?
MSDN Blog - Typing Hard Can Trip You Up (Eric Lippert)

vbscript Type mismatch error when calling function

I am running into the Type Mismatch error when I attempt to call a function I created.
Example:
Function DoThis(paramA, paramB, paramC)
If paramA = "Something" Then
DoThis = DoSomething
ElseIf paramA = "This" Then
DoThis = DoSomethingDifferent
Else
DoThis = DoThisOtherThing
End If
End Function
Dim result: result = DoThis(valueA, ValueB, ValueC)
Can anyone see what my mistake could be? Other functions are working correctly. I have double checked the spelling by actually copying and pasting the function name where I call it. I have verified that the function name is not used anywhere else, i.e., as a constant or something else.
Note that when debugging this the ValType for all arguments is vbString. Also I am never able to enter the function, so it is not like I am debugging the function, enter it and then get the type mismatch.
ty.
VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.
There are some subtypes of data that a Variant can contain (e.g. Empty, Null, string, integer, object, array etc.) You can use some conversion functions to convert data from one subtype to another, if that conversion is not implicit in VBScript. Now, pay your attention to real, factual data subtype of True and vbTrue.
The True keyword (boolean literal) has a value (inner representation) equal to -1.
On the other hand, vbTrue is one of few built-in constants and, in despite of it's name, has a subtype of Integer! It's one of so-called Tristate Constants:
Constant Value Description
vbUseDefault -2 Use default from computer's regional settings.
vbTrue -1 True
vbFalse 0 False
I hope next code could make clear all above statements:
Wscript.Echo _
vbTrue, CStr( vbTrue), VarType( vbTrue), TypeName( vbTrue) , _
vbNewLine, True, CStr( True), VarType( True), TypeName( True)
However, used with If _condition_ Then ..., there are some particularities; in brief:
The Then part of the If ... statement conditionally executes groups of statements only when a single test If condition is not False, i.e. any non-zero number esteems to be true, not only -1. Therefore you are able to use whatever variable or expression (numeric or string) you choose as long as the result is numeric...
Summarizing: If _expr_ Then ... is the same as
If CBool(_expr_) Then ...
The reason why retval is retuning mismatch error because it has a numeric value and an alpha value and wsh does not like that.
A sure way to get a type mismatch error for the published code is to define DoSomething etc. as Subs (which seems probable, given the names).
I cannot explain why this was a problem, but today I reduced the function down to a simple boolean return value and I still got the type mismatch error.
So I then created a new function with the same parameters and such. When I changed the call to the new function the error goes away.
My original function with the simple boolean return:(MISMATCH ERROR)
Function IsInstalledCheck(valueToCheck, expectedValue, checkType)
IsInstalledCheck = vbFalse
End Function
My new function with the a simple return:(Works)
Function IsItemInstalled(valueToCheck, expectedValue, checkType)
IsItemInstalled = vbFalse
End Function
EDIT
Note that I had tried this with the standard True / False values as well. The solution was to simply recreated the same function with a new name and for whatever magical reason that worked. The function signature was the same, the order of variables, variable names, the test conditions, everything in the body of the new function is the same.

VBScript: Finding the number of non-null elements in an array

What is the "best" way to determine the number of elements in an array in VBScript?
UBound() tells you how many slots have been allocated for the array, but not how many are filled--depending on the situation, those may or may not be the same numbers.
First off there is no predefined identifier called vbUndefined as the currently accepted answer appears to imply. That code only works when there is not an Option Explicit at the top of the script. If you are not yet using Option Explicit then start doing so, it will save you all manner of grief.
The value you could use in place of vbUndefined is Empty, e.g.,:-
If arr(x) = Empty Then ...
Empty is a predefined identify and is the default value of a variable or array element that has not yet had a value assigned to it.
However there is Gotcha to watch out for. The following statements all display true:-
MsgBox 0 = Empty
MsgBox "" = Empty
MsgBox CDate("30 Dec 1899") = True
Hence if you expect any of these values to be a valid defined value of an array element then comparing to Empty doesn't cut it.
If you really want to be sure that the element is truely "undefined" that is "empty" use the IsEmpty function:-
If IsEmpty(arr(x)) Then
IsEmpty will only return true if the parameter it actually properly Empty.
There is also another issue, Null is a possible value that can be held in an array or variable. However:-
MsgBox Null = Empty
Is a runtime error, "invalid use of null" and :-
MsgBox IsEmpty(Null)
is false. So you need to decide if Null means undefined or is a valid value. If Null also means undefined you need your If statement to look like:-
If IsEmpty(arr(x)) Or IsNull(arr(x)) Then ....
You might be able to waive this if you know a Null will never be assigned into the array.
I'm not aware of a non-iterative method to do this, so here's the iterative method:
Function countEmptySlots(arr)
Dim x, c
c = 0
For x = 0 To ubound(arr)
If arr(x) = vbUndefined Then c = c + 1
Next
countEmptySlots = c
End Function
As Spencer Ruport says, it's probably better to keep track yourself to begin with.
There's nothing built in to tell you what elements are filled. The best way is to keep track of this yourself using a count variable as you add/remove elements from the array.

Is it better to use NOT or <> when comparing values?

Is it better to use NOT or to use <> when comparing values in VBScript?
is this:
If NOT value1 = value2 Then
or this:
If value1 <> value2 Then
better?
EDIT:
Here is my counterargument.
When looking to logically negate a Boolean value you would use the NOT operator, so this is correct:
If NOT boolValue1 Then
and when a comparison is made in the case of the first example a Boolean value is returned. either the values are equal True, or they are not False. So using the NOT operator would be appropriate, because you are logically negating a Boolean value.
For readability placing the comparison in parenthesis would probably help.
The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.
Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".Here is a quick experiment to prove it:
StartTime = Timer
For x = 1 to 100000000
If 4 <> 3 Then
End if
Next
WScript.echo Timer-StartTime
StartTime = Timer
For x = 1 to 100000000
If Not (4 = 3) Then
End if
Next
WScript.echo Timer-StartTime
The results I get on my machine:
4.783203
5.552734
Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.
If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.
The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as
If NOT (value1 = value2)
which just makes the use of the NOT keyword pointless.

Resources