Article ID: 129803
Article Last Modified on 5/6/2003
Source Type Coerced to Apply this rule
--------------------------------------------------------------
Integer Boolean 0=False, non-zero=True
Boolean Byte False=0, True=255
Boolean any numeric False=0, True=-1
(except Byte)
String Date String is analyzed for mm/dd/yy,
and so on
Date numeric type Coerce to Double and use
DateSerial(Double)
numeric type Date Use number as serial date, check
valid date range
numeric type Byte Error if negative
String numeric type Strings are treated as a Double
when they need to represent a
number
Some of these rules allow for simplified syntax when writing your code. For
example:
ReturnCode% = FunctionThatReturnsAnInteger() If (ReturnCode%) Then ...This piece of code takes advantage of the implicit Integer to Boolean coercion and correctly evaluates the expression in the If statement.
Dim I As Integer, J As Integer Dim L As Long, M As Long Dim S As String I = 32767 L = 32767 M = 1 S = "Hello World!" J = I + 1 ' Overflow. Integer upper limit = 32767. No coercion applied. J = I + M ' Overflow. I+M is coerced to a Long and the value 32768 is generated, ' but when the assignment operator is resolved, this Long value is ' coerced back to Integer (J's type) and overflows. L = I + 1 ' Overflow. Coercion is not applied until the assignment operator is ' resolved. I + 1 'Overflow's the temporary Integer variable created ' to resolve the plus operator. If I Then Print "I is True" If Not I Then Print "Not I is True" ' This prints both 'I is True and Not I is True', a logical ' contradiction. The value of I = 32767, which is non-zero and under ' the Integer to Boolean rule, is coerced to True. With 'Not I', ' the NOT operator is applied first, which produces -32768 which is ' also non-zero and, therefore, True.The following scenario shows how implicit conversion can generate a variety of unexpected results. You can add this code to a new program and run it too see the output.
Private Sub Form_Click()
Call MySub(1, 23) '<-- Note: passing *numbers*!
End Sub
Private Sub MySub (a As String, b As String)
Debug.Print "a = "; a, , TypeName(a)
Debug.Print "b = "; b, , TypeName(b)
Debug.Print "a + b = "; a + b, , TypeName(a + b)
Debug.Print "a + b - 1 ="; a + b - 1, TypeName(a + b - 1)
Debug.Print "1 - a + b ="; 1 - a + b, TypeName(1 - a + b)
Debug.Print "a + b + 1 ="; a + b + 1, TypeName(a + b + 1)
Debug.Print "1 + a + b ="; 1 + a + b, TypeName(1 + a + b)
Debug.Print "(1 + b) / a ="; (1 + b) / a, TypeName((1 + b) / a)
End Sub
The output is:
a = 1 String b = 23 String a + b = 123 String a + b - 1 = 122 Double 1 - a + b = 23 Double a + b + 1 = 124 Double 1 + a + b = 25 Double (1 + b) / a = 24 Double
Keywords: kbinfo KB129803