Search code examples
c#integer-overflow

arithmetic exception in C#


Why in C# is Example A valid, compilable and will just wrap while examples B will not compile?

A

int val = 0;
val = val + Int32.MaxValue +2;

or

int val = Int32.MaxValue;
val++;

B

int val = 0;
val = 2147483647 + 1;

or

int val = 0;
int val = Int32.MaxValue + 1;

I know by default that arithmetic exceptions are not checked by default unless you explicitly do so using checked method, block or attribute in the config. My question relates more to compiler then how an arithmetic exception happens.


Solution

  • Your B examples are constant-folded at compile time, indicating to the compiler that it's guaranteed to overflow.

    Because your A examples use variables, the expressions cannot be (completely) constant-folded, so the compiler can't guarantee that the values will result in an overflow.

    For instance...

    int val = 0;
    // some other thread changes `val` to -5...
    val = val + Int32.MaxValue +2; // no overflow
    

    However, if you know that val won't change, and assign 0 to a const int:

    const int startval = 0;
    int val = startval + Int32.MaxValue + 2;
    

    You can get your compile-time overflow check back because the value can be completely determined and therefore constant-folded.