0

In this case, sum is an int and I am intentionally setting one[] and [two] to int.MaxValue.

The result for sum is 1.

How can I tell if the result of a math function is going to overflow here, prior to attempting it?

sum += one[i] * two[i];
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Patrick
  • 5,526
  • 14
  • 64
  • 101
  • 1
    Simply: you can´t. – MakePeaceGreatAgain Jan 28 '18 at 19:35
  • This might help you https://stackoverflow.com/questions/1657834/how-can-i-check-if-multiplying-two-numbers-in-java-will-cause-an-overflow – MA1 Jan 28 '18 at 19:36
  • What if your maths get more complicated, e.g. `Math.Pow(1231221, 2322)`? It´s impossible to know *before* you execute it and see what happens. – MakePeaceGreatAgain Jan 28 '18 at 19:48
  • @HimBromBeere that is true for any function you call. but I think, question is about basic ops CPU can handle. – L.B Jan 28 '18 at 20:24
  • I did this using the C# `checked()` keyword, which forces it to throw. It's the only way I can catch it and handle it. I don't see any way around it. – Patrick Jan 28 '18 at 20:29

1 Answers1

0

By 'overflow', did you mean it will exceed int.MaxValue? If so, try to use checked block. As @AlexD mentioned in comments, it won't perform a prior-check; however, it will raise an exception in case of overflow.

Quote and code sample are taken from MSDN:

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

// If the previous sum is attempted in a checked environment, an 
// OverflowException error is raised.

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}
Ian H.
  • 3,840
  • 4
  • 30
  • 60
Aly Elhaddad
  • 1,913
  • 1
  • 15
  • 31