Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么CLR不';t编译溢出常量,但对于变量它会编译吗?_C#_.net_Clr - Fatal编程技术网

C# 为什么CLR不';t编译溢出常量,但对于变量它会编译吗?

C# 为什么CLR不';t编译溢出常量,但对于变量它会编译吗?,c#,.net,clr,C#,.net,Clr,看到下面的代码,我只是想了解背后的原因 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,所以a+b将失败。 但是对于其他变量,它

看到下面的代码,我只是想了解背后的原因

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
,所以
a+b
将失败。
但是对于其他变量,它们可以在运行时更改,因此编译器不会假定设置的值不会更改为有效值。

对于常量值,编译器基本上在编译时用常量值替换变量。因此,在编译时对addition语句求值时,它能够知道值并查看溢出情况

对于整型变量,我认为编译器在编译时不会考虑指定的值,而是在运行时计算表达式

但C#的结果是默认情况下禁用了检查。您可以在选项中启用它。请参阅Justin Ethernedge关于“为什么”和“如何”的精彩博文:


const
表达式在编译时解析,非
const
表达式在运行时解析。默认情况下,每个都有不同类型的溢出检查上下文。根据C#规范:

对于非常量表达式(在 未由任何选中或未选中的运算符包围的 或语句,默认溢出检查上下文未选中 除非外部因素(如编译器开关和执行 环境配置)调用已检查的评估

这就是为什么在使用局部变量进行运算时没有看到运行时错误。至于
常数
计算:

对于常量表达式(可以在 编译时),默认溢出检查上下文始终为 选中。除非常量表达式显式放置在 未选中的上下文,编译时发生的溢出 表达式的求值总是导致编译时错误

这就是为什么您在
const
计算中看到编译时错误的原因


.

只是猜测,但肯定是因为它们是常量,编译器可以明确地看到,当添加它们时,它们将溢出,而使用变量时,它将值视为未知。旁注:CLR不编译C源代码,这是C编译器的工作。但即使在运行时,它也不会对溢出条件引发异常