4

Using the immediate window to do some debugging, I came across the following which I have simplified for the purpose of this question:

running this command:

?20000*2

produces an 'overflow' error. Let's assume this is because we haven't declared a data type, and VBE has assumed Integer - the result falls outside the boundaries of a signed integer and therefore an overflow occurs.

However if I run:

?39999+1

I get 40000 as expected.

Is this because I've initially started with a Long instead of an Integer (i.e. 20,000 vs 39,999)? And therefore memory is allocated based on the initial input data rather than the calculation result?

SierraOscar
  • 17,507
  • 6
  • 40
  • 68

2 Answers2

6

That's correct. VBA will take the largest of the input components and allocate memory for the results. Since both of the components in the first example are Int, that's all you get.

You can use a type declaration character to force the VBE to treat a number as a certain data type

?20000&*2
 40000 
?20000*2&
 40000 

In both those examples, the & (Long type declaration character) forces the memory allocation to a Long. It doesn't matter if it's the first component or a later one. I think there are some operations that get forced into particular data types. Exponentiation is one of them.

?2^2^2^2^2^2
 4294967296 
?typename(2^2^2^2^2^2)
Double

Even though all the components are Integers, the results is a Double - even when it doesn't have to be

?typename(2^2)
Double
Dick Kusleika
  • 32,673
  • 4
  • 52
  • 73
  • This is an excellent answer, thanks. I didn't think to try the type declarations and I didn't realise that certain operators would default to certain data types - so this was extremely informative! – SierraOscar Apr 17 '15 at 19:00
5

This implicit typing isn't limited to the Immediate Window. The same overflows can occur in your code:

Sub foo()

  Dim x As Long

  x = 20000 * 2 'Overflow error

End Sub

Also, when a String is implicitly cast to a numeric type, it's cast as a Double:

?TypeName("123" + 6)
Double
ThunderFrame
  • 9,352
  • 2
  • 29
  • 60
  • @MacroMan - It's 2 separate operations - a multiplication, then an assignment. Both of the operands are in the integer range, so it only allocates an integer return value. It doesn't check whether the *assignment* overflows until after it has a result, but by that time it's already overflowed. – Comintern Dec 22 '16 at 22:51
  • Jeez, say what you want about javascript but at least you know where you stand! – SierraOscar Dec 22 '16 at 23:04