Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

puzzling thigs in VB I am trying to figure out:

18 * 60000 gives me back

1080000

while 40 *1000 overflows!

Why?!!!

18 * 60000 gives me back

1080000

while 40 *1000 overflows!

Why?!!!

in your example:

40 * 1000 = overflow

40 will be considered an integer

1000 will also be considered an integer because integers range from -32,768 to 32,767. So in effect you are multiplying two integers and the result should also be an integer. Since the result is 40,000 which is bigger than the max integer value, we have an overflow.

18 * 60000

the compiler will treat the 60000 as a Long since it can represent the value.

In effect, we are multipliying longs which will also give us a Long.

the range of longs is -2,147,483,648 to 2,147,483,647. So the result is within range.

To avoid this kind of problem, make sure that you define your variables correctly.

40# * 1000#

will NOT overflow. Sometimes dynamic typing helps, sometimes dynamic typing hurts.

You'ld think that VB would be smart enough to look at the *entire* equation and find the largest type and work the problem that way instead of hunting for the smallest type and generation stupid overflow errors.

If you code:

DIM Result as Double

Result = 40 * 1000

It'll still overflow even tho the receiving var is explicitly typed as a double. The right side is all integers and therefore is performed in integer math.

One really screwy thing that shows the effects of dynamic typing is:

DIM A as Double

DIM B as Double

DIM C as Double

A = 40

B = 1000

C = A * B

This will *still* overflow even though all of the vars are explicitly typed as Doubles. The assignments 'A=40' and 'B=1000' are both assigning integer values to Double Vars - and VB dutifully notices that only integers are needed and so A and B are dynamically retyped as Integers and the 'C = A * B' statement chokes.

So, the lesson is that you should make sure your numerical constants are typed the same as your vars. Using:

A = 40#

B = 1000#

will cause the compiler to treat the numerics as doubles (you can also enter 40.0 and 1000.0) and will prevent dynamic typing from biting you.

M

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.

You can do something like 40 * CLng(1000) to make sure the 1000 is interpreted as a Long variable and therefore the whole expresion will be of Long type.