See the code below, I just want to understand the reason behind that...
const int a = 2147483647;
const int b = 2147483647;
int c = a + b; // it doesn't allow to compile!!!
int a = 2147483647;
int b = 2147483647;
int c = a + b; // it allows to compile!!!
const
expressions are resolved at compile-time, non-const
expressions are resolved at runtime. Each have different types of overflow checking contexts by default. According to the C# specification:
For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.
Which is why you're not seeing a runtime error when you use local variables to do the arithmetic. As for the const
calculation:
For constant expressions (expressions that can be fully evaluated at compile-time), the default overflow checking context is always checked. Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression always cause compile-time errors.
Which is why you're seeing a compile-time error with your const
calculation.
More information about checked and unchecked on MSDN.
For constant values, the compiler essentially replaces the variable with the constant value at compile time. Therefore, when the addition statement is evaluated at compile time, it is able to know the values and see the overflow condition.
For the integer type variables, I don't think the compiler actually takes the assigned values into account at compile time, but rather evaluates the expression at runtime.
But C#, turns out that check is disabled by default. You can turn it on in the options. See Justin Etheredge's excellent blog post on the whys and how's:
http://www.codethinked.com/c-trivia-what-no-overflow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With