Integer and String comparison conflict in VBScript

坚强是说给别人听的谎言 提交于 2019-12-23 18:02:26

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/40465831/integer-and-string-comparison-conflict-in-vbscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!