Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic Classic (6 and earlier)
Expertise: Beginner
Sep 14, 2016

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 Long
Const 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
Oracy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date