gpt4 book ai didi

c# - 为什么相加两个结果大于 int.MaxValue 的大整数不会抛出溢出异常?

转载 作者:行者123 更新时间:2023-11-30 13:50:13 26 4
gpt4 key购买 nike

如果我们在程序中使用以下循环,在 C# 4.0 中循环永远不会结束

for (int i = 1; i <= int.MaxValue; i++)
{
}

这是因为int.MaxValue(2147483647)加1不会产生溢出异常,而是-2147483648(考虑到32bit int和2的补码)。

int i = int.MaxValue;
Console.WriteLine(i + 1);

最近行为似乎发生了变化。 See the question Arithmetic operation caused OverflowException .此更改背后的原因可能是什么?

最佳答案

整数(和其他整数类型)的溢出异常仅在 checked 中完成上下文。

因此,这将导致异常:

checked
{
int i = int.MaxValue;
Console.WriteLine(i + 1);
}

默认情况下它们不会设置为执行此操作,因为它们比简单溢出更昂贵。

来自 MSDN:

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

和:

Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.


这不是最近的变化——C# 从第一天起就是这样。您在问题中看到的是 VB.NET 代码,默认情况下它位于已检查的上下文中。

因此,保持默认值,VB.NET 中的溢出代码将引发异常,但 C# 中的相同代码不会。

关于c# - 为什么相加两个结果大于 int.MaxValue 的大整数不会抛出溢出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7122473/

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