Gary Milne Active Member Licensed User Longtime User Dec 30, 2015 #1 This code: Code: Dim Diff1 As Long = (999999 * 1000) Log ("Diff1 is:" & Diff1) Dim Diff2 As Long = (999999 * 2000) Log ("Diff2 is:" & Diff2) Dim Diff3 As Long = (999999 * 3000) Log ("Diff3 is:" & Diff3) Dim Diff4 As Long = 2147483647 + 1 Log ("Diff4 is:" & Diff4) Generates this output. Diff1 is:999999000 Diff2 is:1999998000 Diff3 is:-1294970296 Diff4 is:-2147483648
This code: Code: Dim Diff1 As Long = (999999 * 1000) Log ("Diff1 is:" & Diff1) Dim Diff2 As Long = (999999 * 2000) Log ("Diff2 is:" & Diff2) Dim Diff3 As Long = (999999 * 3000) Log ("Diff3 is:" & Diff3) Dim Diff4 As Long = 2147483647 + 1 Log ("Diff4 is:" & Diff4) Generates this output. Diff1 is:999999000 Diff2 is:1999998000 Diff3 is:-1294970296 Diff4 is:-2147483648
R Roycefer Well-Known Member Licensed User Longtime User Dec 30, 2015 #2 This is expected and normal behavior. In all 4 cases, you're doing operations on two Ints and then assigning the resulting value to a Long. Consequently, the Int overflow will occur before a Long is created and any values are stored in it. Instead, try this: Code: Dim Diff3 As Long = 999999 Diff3 = Diff3 * 3000 Log("Diff3: " & Diff3) This makes sure that 999999 is stored in a Long and that the resulting 999999*3000 is performed as Long multiplication and not Int multiplication.
This is expected and normal behavior. In all 4 cases, you're doing operations on two Ints and then assigning the resulting value to a Long. Consequently, the Int overflow will occur before a Long is created and any values are stored in it. Instead, try this: Code: Dim Diff3 As Long = 999999 Diff3 = Diff3 * 3000 Log("Diff3: " & Diff3) This makes sure that 999999 is stored in a Long and that the resulting 999999*3000 is performed as Long multiplication and not Int multiplication.
Gary Milne Active Member Licensed User Longtime User Dec 30, 2015 #3 Thank you, that does explain it in that the right hand side is evaluated first. I think making the temporary value that holds the Int * Int of the same type as the left hand side would be more intuitive. Don't mind the rules though as long as I know what they are.
Thank you, that does explain it in that the right hand side is evaluated first. I think making the temporary value that holds the Int * Int of the same type as the left hand side would be more intuitive. Don't mind the rules though as long as I know what they are.