tags:

views:

35

answers:

2

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?

A: 

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.

pkauko
Thanks pkauko for sharing you thoughts
Pradeep
Alhtough I must say I don't disagree with MarkJ in the least, so I'd say you should do as he suggests assuming you're not extremely tight on memory (in which case you'd probably be coding in C or some such) or, as he says, there are millions of instances of these variables in use simultaneously.
pkauko
+1  A: 

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.

MarkJ