Tuesday, July 26, 2005

Interesting Bug/Feature of VB6


I haven't blogged for the longest time, me and my wife have been settling in into married life and our rented apartment. Much has been going on in my life in the last couple of months. for example I have married my beatifull wife, I have also gotten in to a new hobby - woodturning, which I really love (ranting - again it is proven that leaving in the USA is much more cost effective for me - imagine the cost of importing a wood working Lathe and tools - it is huge!).

Anyway, back to the main topic, VB6 and it's quirks. I have been programming with VB6 for the last 4 years at least, and this is the first time that I encountered this feature/bug (you decide, in my case it was a bug). I had a case where I test two boolean varaiables against each other (x=y) and both where True, but the comparison returned false!!! the result of the statement is that True<>True - you can agree that this is wierd....

After a lot of debugging work and a lot of help from friends here, we found the reason. when printing the Cint() value of the Booleans, one of them equalled 1 and the other equalled -1 (-1 is the VB value for True, however VB  considers anything not 0 to be true). Since VB apparently checks the Int value of the Boolean variables.

Why did this happen, well, it turns out that if you send a boolean to a function byref, and the function interface is declared as Variant. When assigning “1” to the boolean inside the function and exiting. the boolean value is set to True (as should be) but it's int is set to 1 instead of -1. Here is a code example

Function First()
     Dim a As Boolean
     Dim b As Boolean
     Dim c As Boolean
a = True
b = True
c = True

MsgBox (a=b) ' will print True
MsgBox (a=c) 'will print True

Call Second(c)

MsgBox (a=b) ' will print True
MsgBox (a=c) 'will print False
MsgBox(a) ' Will print True
MsgBox(c) ' Will print True

End Function

Function Second(ByRef par As Variant)
      par = “1“
End Function