Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 253
Shubham Kundu Avatar asked Oct 27 '25 14:10

Shubham Kundu


1 Answers

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)
like image 155
user692942 Avatar answered Oct 30 '25 14:10

user692942



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!