Post

More on Remove Integer Overflow Checks

The following is taken from the online documentation:

However, without error checking and if data type capacities are overflowed, incorrect results may be stored without raising an error.

The question that comes to my mind is what exactly will happen if an overflow does occur and an error isn’t thrown (because we’ve turn off overflow checking).  My initial guess is that it will behave like C# does and just roll over the value, dropping the overflow amount.  And it appears that my guess is correct.

1
2
3
4
5
6
7
8
9
10
11
Dim value As Short = 32000
Try
  Do
    value = value + 1000
    If MsgBox(value.ToString & vbCrLf & "Try again?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
      Exit Do
    End If
  Loop
Catch ex As Exception
  MsgBox(ex.Message)
End Try

I’m using a short since it’s easier to get to an overflow point.  Starting off with 32000 we add 1000 which would cause the overflow to occur since the maximum value of a short is 32767.  What will the result be?  -32536.  The overflow occurs at 32768, which leaves us a remainder of 232.  The minimum value for a Short is -32768.  If you add 232 to this value, you will end up with the result returned to us in the sample.  So rather than look at it as a “incorrect results may be stored”, if you know what will happen, you might be able to use this to your advantage ;-)

This post is licensed under CC BY 4.0 by the author.