tags:

views:

43

answers:

2

Let's say I have any array Trial() As Integer
I have two following variables defined as Integer:

Dim Left As Integer
Dim Right As Integer

Now I am increasing the array index of trial

ReDim Preserve Trial(Left+Right)

Now If My total (Left+Right) exceeds Integer limit the above will give error.
And if redeclared Left as Long then it will work fine.

Actually I want to understand the internal calculation for (Left+Right).
Does it allocate the space for total depending on the datatype of "Left"?
Or it may also depends on datatype of "Right"?

+1  A: 

It depends on both. The compiler will examine both variables and determine from both what data type it needs. For example. If you were to add (or multiple or divide) an Integer and a Long then the result will give you a long.

Zippit
+1. Also worth mentioning that it only looks at the calculation it's doing at the time. So `CLng(Left)*(Left+Right)` would still give you an overflow on the `Left+Right` because it does that part as integers. By the time it gets to `CLng(Left)*` it will expand to Long.
MarkJ
A: 

The calculation Left + Right is done presuming the result was an integer too, that's where the overflow occurs.

If you go CLng(Left) + CLng(Right) first, it is done the same way, only that the result will be a long, and thus no overflow occurs.

clausvdb