Arithmetic bug?

I have this code:

dim d as int64
d = 1291563182 + 2082844800
msgbox(str(d))

Result: -920559314

How do I persuade the compiler to treat my numeric literals as 64-bit rather than 32-bit?

This is causing my attempts to do:

dim dt as new date
dt = new date
dt.totalseconds = d
msgbox (str(dt))

to give me a date in 1874 rather than 2010 as expected (2082844800 is, I hope, the number of seconds between 1/1/1904 and the unix epoch).

Use CType?

d = Ctype(1291563182,int64) + ctype(2082844800,int64)

I’m not sure that solves all situations, but it does work for this one.

Do you have xDev? I wrote an article about exactly this two issues ago.

Think about what type of number you have on the right side of the equation.

When you know the answer you’ll realize that you’ll get an integer overflow error.

So make sure you are adding up the right number types.

Btw this type of error is fairly easy to spot when you add up numbers, but becomes more tricky when you add up variables.

simple workaround but it works :

dim d as int64 d = 1291563182.0 + 2082844800.0 msgbox(str(d))

But it only works in the range of a double. You will eventually lose precision before you overflow the int64.

I got around this by coding this way:

dim d as int64
d = d + 1291563182 + 2082844800
msgbox(str(d))

Interesting replies - thanks.

But I am nonetheless puzzled. Is this not a case of constant folding, which I would expect to be done with as large a precision as possible (assuming the principle of least surprise)? Suppose I said:

d = 100 + 110

and I did that because the numbers (100, and 110) each had some specific meaning, would that provoke overflow because each will fit in an int8 but the sum does not? What about if I had defined those numbers as constants - how wide is a constant?

I like Rolf’s answer but does that involve two additions at runtime?

I looked for but couldn’t find information about casting and what the definition of a number is. Something like this page would be useful:

http://www.php.net/manual/en/language.types.integer.php

Anyway now I am warned about this I can watch out for it. It’s what comes of having used loosely typed languages for so long.

You need to make sure to define ‘d’ prior to its use. Otherwise you are leaving it up to the compiler to define it, and you don’t know what that will look like (same thing as it is happening now - as it appears the base units of the compiler are 32bits; which means you should implicitly cast any number which is not 32bits if you want to guarantee the answer).