c# – 使用常量进行算术运算时出现溢出错误

我尝试了以下代码:

int x, y;
x = y = int.MaxValue;

int result = x + y;

这段代码工作正常,结果将包含-2(我知道为什么).

但是当这样做时:

const int x = int.MaxValue;
const int y = int.MaxValue;

int result = x + y;

这不会因为溢出问题而编译.为什么?

因为x和y都是编译时常量,所以x y也是.编译器知道结果将溢出,所以它抱怨.

您可以使用未选中的表达式来解决此问题:

int result = unchecked(x + y);

从C#5规范第7.6.12节 – 上市后, – ,/和*:

When one of the above operations produce a result that is too large to represent in the destination type, the context in which the operation is performed controls the resulting behavior:

  • In a checked context, if the operation is a constant expression (§7.19), a compile-time error occurs.
  • In an unchecked context, the result is truncated by discarding any high-order bits that do not fit in the destination type.

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.

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.

翻译自:https://stackoverflow.com/questions/19735040/overflow-error-when-doing-arithmetic-operations-with-constants

转载注明原文:c# – 使用常量进行算术运算时出现溢出错误