Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overflow error with simple math 5

Status
Not open for further replies.

zemp

Programmer
Jan 27, 2002
3,301
CA
VB6 SP6

I have a variable declared as a long. I can assign it a value of 34000 with no problems. However when I try to assign it a sum that equals 34000 I get the overflow error.

For example
Code:
Dim MyLng as Long
MyLong = 34000  ' works
MyLong = 32000 + 2000    'error 6, overflow
I also get the same results in the immediate window with the above code and
Code:
?32000 + 2000

How can I overcome this? It seems to be an integer vs. long issue within VB but I just can't see it.

zemp
 
Since you have 2 constants on the right side of the equal that can be converted to integer, this is what happens. Since they are both integers, you get the overflow. You could try....

Code:
MyLong = [!]CLng([/!]32000[!])[/!] + [!]CLng([/!]2000[!])[/!]    [green]'no more error[/green]

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
I knew I was just not seeing something. I had tried the long conversion around the sum but I didn't even think of converting each before the sum was done.

Thanks George.

zemp
 
zemp,

I'm glad I could help.


Just to clarify (for other readers)...

If you do:

Debug.Print TypeName(32000)
Debug.Print TypeName(2000)

You will get Integer. So, both values on the right side of the equation are integers. When adding the values, it adds them as integers. Finally, when you assign it to the variable (type Long), VB will convert the value for you. Essentially, you have...

Long = Integer + Integer

The Integer + Integer is evaluated before the assignment. The values given cause an overflow error.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Besides the CLng function, you can also use & type specifier to make your numbers Long.
[tt]
MyLong = 32000& + 2000&
[/tt]
The ampersand (&) operator tells the compiler to treat the number as Long, instead of default Integer, you can see this in the immediate window:
[tt]
?typename(32000),typename(32000&)
Integer Long[/tt]
 
Thanks gmmastros and hypetia for the answer and zemp for the question. I'm up against the same thing!!!!!

I tried to have patience but it took to long! :) -DW
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top