0

This is just a basic sum method.

public int Sum(int a, int b)
{
    return a + b;
}

If I call the function as below

int result = Sum(int.MaxValue, int.MaxValue);

Why am I gettin ‘-2’ in the result variable even though there is an overflow. Shouldn't I get a stackoverflow exception?

  • 3
    Not a stack overflow, but an [integer overflow](https://en.wikipedia.org/wiki/Integer_overflow) – Mureinik Jan 04 '23 at 17:38
  • 2
    Because that's what checked code does. It overflows. Why would you expect a stack overflow? This doesn't have anything to do with exceeding the stack. – David L Jan 04 '23 at 17:38
  • And here's another question which addresses how to prevent this: [What is the C# "checked" keyword for?](https://stackoverflow.com/questions/20709495/what-is-the-c-sharp-checked-keyword-for) – Joe Sewell Jan 04 '23 at 17:53
  • Docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#arithmetic-overflow-and-division-by-zero "In an unchecked context, the result is truncated by discarding any high-order bits that don't fit in the destination type." (and shows example similar to this question) – Alexei Levenkov Jan 04 '23 at 18:07

0 Answers0