Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why CLR doesn't compile overflow const and but for variables it does?

Tags:

c#

.net

clr

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!!!
like image 842
RollRoll Avatar asked Dec 07 '12 01:12

RollRoll


2 Answers

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.

like image 79
Andrew Whitaker Avatar answered Sep 29 '22 05:09

Andrew Whitaker


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

like image 23
Brian Knight Avatar answered Sep 29 '22 05:09

Brian Knight