Adding Longs Without Overflowing

Adding Longs Without Overflowing

Suppose you are porting a C code, for example, that sums 32 bit integers (Longs) to VB6. In C, when the result of a sum does not fit into an integer, it overflows silently. In VB, you will get a nasty runtime error instead.

So, this is a handy function to have under your belt: It adds two Longs and “silent overflows” if needed.

Public Function Add(ByVal LeftValue As Long, ByVal RightValue As Long) As LongConst ADJUST As Double = 4294967296#Dim Result   As Variant    Result = CDec(LeftValue) + CDec(RightValue)        Select Case Result        Case Is              Result = Result + CDec(ADJUST)                    Case Is  2147483647            Result = Result - CDec(ADJUST)    End Select        Add = CLng(Result)End Function


Share the Post: