views:

199

answers:

1

We are currently having an issue due to implicit conversion in an IF statement in VBScript (Classic ASP) that don't do implicit conversion the same way when dealing with a variable or a literal. Can someone explain this behavior to me, why do VBScript acts this way ?

Here is a sample of what I mean :

Const c_test = 3
Dim iId : iId = 3
Dim iTestStr : iTestStr = "3"

If iId = iTestStr Then
    Response.Write("Long variable = String variable : Equal")
Else
    Response.Write("Long variable = String variable : Not Equal")
End If

Response.Write("<br/>")

If c_test = iTestStr Then
    Response.Write("Long constant = String variable : Equal")
Else
    Response.Write("Long constant = String variable : Not Equal")
End If

Response.Write("<br/>")

If c_test = iId Then
    Response.Write("Long constant = Long variable : Equal")
Else
    Response.Write("Long constant = Long variable : Not Equal")
End If

Response.Write("<br/>")

If iId = "3" Then
    Response.Write("Long variable = String literal : Equal")
Else
    Response.Write("Long variable = String literal : Not Equal")
End If

Response.Write("<br/>")

If c_test = "3" Then
    Response.Write("Long constant = String literal : Equal")
Else
    Response.Write("Long constant = String literal : Not Equal")
End If

Which ouputs :

Long variable = String variable : Not Equal

Long constant = String variable : Not Equal

Long constant = Long variable : Equal

Long variable = String literal : Equal

Long constant = String literal : Equal

Which is quite confusing o_O

+1  A: 

You are (implicitly) declaring your variables As Variant so your If conditions actually test the equality of two Variants and determine that they are unequal.

In the last cases, however, you are using String constants (which can never be Variant, even if declared without a type) and String literals.

My guess is that when you compare two Variants, VB first determines whether they have the same type tag and if they don’t, resolves to False.

Konrad Rudolph
I tested the types of variables and constants with VBScript function "VarType", and none of them is Variant, it turns out that they are vbInteger (for the iId and c_test) and vbString for iTestStr. By the way, VBScript does not allow variable type declaration.
MaxiWheat
@Maxi: I had forgotten that. But the variables are *still* of type `Variant`, and `VarType` actually *extracts* the type tag from a `Variant`, which is why you get another result. `VarType` may also return `vbVariant`, but this is only the case for *arrays* of `Variant`s.
Konrad Rudolph
I will accept your solution which seems logic, even if I have no way to confirm it's absolutely right ;-)
MaxiWheat