为什么C#编译器没有抛出任何错误?
下面是一段代码:为什么C#编译器没有抛出任何错误?,c#,C#,下面是一段代码: { int counter = 1; try { while (true) counter*=2; } catch (Exception) { Console.WriteLine(counter); Console.ReadLine(); } }
{
int counter = 1;
try
{
while (true)
counter*=2;
}
catch (Exception)
{
Console.WriteLine(counter);
Console.ReadLine();
}
}
当我运行这段代码时,经过几次迭代,“counter”的值变为0。
我不明白为什么会这样?使用
选中的来抛出溢出异常:
checked {
int counter = 1;
try {
while (true)
counter *= 2;
}
catch (Exception) { // Actually, on integer overflow
Console.WriteLine(counter);
Console.ReadLine();
}
}
编辑:发生了什么事
事实:整数乘以2等于左移位乘以1,即
counter * 2 == counter << 1
下一个,第32次迭代可能导致整数溢出或
未选中
只需将最左边的1推出即可
0000000000000000000000000000000 // 32nd itterartion, now we have 0
当计数器达到int.MaxValue时,计数器*2变为负整数
当计数器达到int.MinValue时,计数器*2变为0
然后在每次迭代中,你有0*2=0,没有异常抛出。多少是“几次迭代”?那么,当您期望它到达代码的异常部分时,它没有到达代码的异常部分?在你的问题中,我们需要更多的解释,但它听起来确实像一个整数溢出0*2=0-没有错误…没有什么需要捕捉的…我不确定我是否理解问题标题和问题主体之间的关系。你在问什么?为什么会变成0?这与C#编译器抛出错误有什么关系?错误是关于什么的?检查@JohnOdom应该是32:)实际上它将上升到1073741824,然后是int.MinValue
,然后是0。
0000000000000000000000000000000 // 32nd itterartion, now we have 0