gpt4 book ai didi

c# - 整数溢出异常

转载 作者:太空狗 更新时间:2023-10-29 22:30:26 25 4
gpt4 key购买 nike

为什么我在这里得到一个编译器错误:

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; 编译器可以预测 statement(a) 的结果并且它会知道它会导致溢出,因为两者214748364710 是常量,它们的值在编译时已知。

但是当你有

int ten = 10;
int b = 2147483647 + ten;

某些其他线程(或其他线程,可能是向导,可能是内存中的危险......)可能在执行 int b = 2147483647 + ten 之前更改了 ten 的值; 语句和溢出在编译时无法预测。

关于c# - 整数溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com