C# 变量和常量在溢出期间的行为不同。

标签 c# variables compiler-errors compilation constants

 const int cMax = int.MaxValue;
 int vMax = cMax;
 int int1;
 int int2;
 int1 = cMax + 10;//Checked amd throws error
 int2 = vMax+10;//Unchecked and Overflows at runTime

这里可以看到涉及常量的操作默认是被检查的,而涉及变量的操作是未检查的并且通过了编译。

为什么编译行为会出现这种差异?

最佳答案

行为不同,因为 cMax + 10 是常量表达式。根据C# Language Reference ,

A constant expression is an expression that can be fully evaluated at compile time. A constant can participate in a constant expression, as follows:

public const int c1 = 5;  
public const int c2 = c1 + 100;

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.

因此,编译器必须在编译时评估您的表达式。由于它无法生成有效值作为计算结果,因此会产生编译时错误。使用 checked keyword启用整数溢出检查。

关于C# 变量和常量在溢出期间的行为不同。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310220/

相关文章:

c# - 多个where linq

c# - 如何更新绑定(bind)到 WPF 中的集合的 ListView 项?

javascript - 将字符串替换为其他带有字符串的变量

macos - MacOS Sierra xgboost jvm软件包安装错误

c++ - 在不让客户端等待程序执行的情况下限制构造函数可以采用的值

c# - Jquery Fullcalendar (arshaw's) 事件不可编辑

c# - 提高将数据上传到数据库的性能

javascript - js 更改变量会影响原始变量

python - 如何输入变量并将其作为普通文本读取

c - 包含来自另一个目录的头文件