整数溢出异常
Integer overflow exception
为什么我在这里遇到编译器错误:
int a = 2147483647 + 10;
而不是这里,如果我正在执行相同的操作:
int ten = 10;
int b = 2147483647 + ten;
我正在学习 checked 的用法,MSDN 网站不清楚为什么在第一个代码片段中引发 OverflowException:
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.
它只解释行为,不解释行为的原因。我想知道引擎盖下发生了什么。
原因是当你有 int a = 2147483647 + 10;
编译器可以预测语句 (a
) 的结果并且它会知道它会导致溢出,因为 2147483647 和 10 是常量,它们的值在编译时已知。
但是当你有
int ten = 10;
int b = 2147483647 + ten;
某些其他线程(或其他线程,可能是向导,可能是内存中的危险......)可能在执行 int b = 2147483647 + ten;
语句之前更改了 ten
的值,并且溢出可以在编译时无法预测。
为什么我在这里遇到编译器错误:
int a = 2147483647 + 10;
而不是这里,如果我正在执行相同的操作:
int ten = 10;
int b = 2147483647 + ten;
我正在学习 checked 的用法,MSDN 网站不清楚为什么在第一个代码片段中引发 OverflowException:
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.
它只解释行为,不解释行为的原因。我想知道引擎盖下发生了什么。
原因是当你有 int a = 2147483647 + 10;
编译器可以预测语句 (a
) 的结果并且它会知道它会导致溢出,因为 2147483647 和 10 是常量,它们的值在编译时已知。
但是当你有
int ten = 10;
int b = 2147483647 + ten;
某些其他线程(或其他线程,可能是向导,可能是内存中的危险......)可能在执行 int b = 2147483647 + ten;
语句之前更改了 ten
的值,并且溢出可以在编译时无法预测。