devxlogo

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
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist