Bug? Variable defined as Long acts link Int

Gary Milne

Active Member
Licensed User
Longtime User
This code:
B4X:
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
 

Roycefer

Well-Known Member
Licensed User
Longtime User
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:
B4X:
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
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.
 
Top