Pradeep
Pradeep

Reputation: 3468

handle the total of Integers exceeding Long

I have the following code :

Dim L as Integer
Dim R as Integer
Dim a as Integer

a=((L+R)/2)

Now (L+R) exceeds limit of Integer. In order to handle this case: I have following three options:

  1. Define L (or R) as Long
  2. Write a= ((CLng(L)+R)/2)
  3. Declare new variable as Long :

Like this

Dim S as Long
S=S+L+R

I am confused which one is the best to implement?

Upvotes: 0

Views: 120

Answers (2)

MarkJ
MarkJ

Reputation: 30398

Change all the variables to Long.

  • The code will be more robust.
  • The code will execute faster.
  • The additional 2 bytes of memory per variable is totally insignificant, unless you have many millions of these integer variables in use simultaneously.

You've already posted several questions here about integer overflow errors. With all respect, I really advise you to just change all your Integer variables to Long and get on with your coding.

Upvotes: 1

pkauko
pkauko

Reputation: 492

I'd pick #2. I think (not sure) that this uses a little less memory than #1 because there's only one Long -value in the equation where as changing L or R to Long would require space for 2 Long values.

I'm thinking #2 and #3 might end up looking the same (or pretty damn close) after compile and I personally think that in this case an extra variable wouldn't make it more readable. The difference of course is that in #2 the result of the L+R might not need to be saved anywhere, but only moved between registers for the calculation.

I'm thinking alot here, but I'm posting this partly because I hope that if I'm wrong, someone would correct me. Anyway, with the reasoning above, I'd go with #2. Edit: at least I'm quite certain that if one of the options uses less memory than the others, it's #2, but they might all be the same in that regard.

Upvotes: 0

Related Questions