Arithmetic exception in C #

Why is there an Acceptable, compiled example in C # and will just be wrapped until examples B are compiled?

BUT

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

or

 int val = Int32.MaxValue; val++; 

IN

 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 use this using a proven method, block, or attribute in the configuration. My question is more related to the compiler than arithmetic exception then occurs.

+6
c # integer-overflow
source share
3 answers

Your examples B is a bend constant at compile time, indicating to the compiler that it guarantees overflow.

Since your examples use variables, expressions cannot be (completely) added at a constant speed, so the compiler cannot guarantee that the values ​​will lead to overflow.

For example...

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

However, if you know that val will not change and assign 0:

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

You can get a compile-time overflow check because the value can be fully determined and therefore permanently added.

+16
source share

I know arithmetic exceptions are not checked by default, unless you explicitly do this using a proven method, block or attribute in config

You do not know, because this statement is incorrect. And in fact, you know that this is not true, because you provided a case where your statement turned out to be false!

I refer you to section 7.6.12 of the C # specification, a portion of which I will reproduce here for your convenience:

For non-constant expressions (expressions that are evaluated at runtime) that are not enclosed in any checked or unchecked statements or statements, the overflow check context is not set by default if external factors (such as the compiler and runtime configuration) are checked.

For constant expressions (expressions that can be fully evaluated at compile time), the default overflow check context is always checked. If a constant expression is not explicitly placed in an uncontrolled context, overflows that occur during evaluation of the compilation time of an expression always cause compile-time errors.

See the specification for details.

+3
source share

This is simply due to the limitations of compile-time checking. Certain things can only be known at runtime.

+1
source share

All Articles