# Thread: Arithmetic overflows

1. ## Arithmetic overflows

Hi again, simple question:
If I have some calculation like:
Code:
`int val = (int)exp*3600000/(uint)time`
And say exp is 4000, time is nearly 3600000, will the calculation cause an overflow because it calculates 4000*3600000 = 14400000000 first? Or is this compiler specific, or can I control it via:
Code:
`val = exp*(3600000/time)`
Thanks in advance.

2. I'd guess that the first is compiler specific, and I'd do the second one first, yeah.. Parenthesis precedence should keep it from overflowing.

3. Yeah, i'd divide first as long as you are in no risk of losing precision. Your second example makes no difference however as divide has precedence over multiplication. Alternatively you could always use a larger datatype, say Uint64. Or you could test for an overflow.

4. Your second example makes no difference however as divide has precedence over multiplication.
Actually, they have the same precedence. Consequently, I think that the grouping is necessary.

5. Really, I thought it worked using BODMAS?

Edit: Yeah, you are right. So what would evaluate first? would it be left to right?

6. I think so. I think most arithmetic operators are from left to right except the '=', '+=', '-=', etc.

7. Equal precedence operators are evaluated left to right.

As to the original question: You will need to know the range of the respective numbers to decide which order is best for the calculation - in this example it seems that the 3600000/time is a good way to go, but if time is a larger number than 3600000, it would result in zero, and you would end up with bad result.

--
Mats

8. Thanks for you answers.

As exp and time tend to vary between minus several million and plus several million, I choose to use float variables instead of integers. Grants me an extra bonus to precision too. I multiply first now by the way.

Popular pages Recent additions