Why C# compiler is not throwing any error?
本问题已经有最佳答案,请猛点这里访问。
以下是一段代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | { int counter = 1; try { while (true) counter*=2; } catch (Exception) { Console.WriteLine(counter); Console.ReadLine(); } } |
当我运行此代码时,经过几次迭代," counter"的值变为0。
我不明白为什么会这样?
使用
1 2 3 4 5 6 7 8 9 10 11 12 | checked { int counter = 1; try { while (true) counter *= 2; } catch (Exception) { // Actually, on integer overflow Console.WriteLine(counter); Console.ReadLine(); } } |
编辑:这是怎么回事。
事实:整数乘以2等于左移1,即
1 | counter * 2 == counter << 1 |
就您而言(让
1 2 3 4 5 | 00000000000000000000000000000001 // initial, just 1 00000000000000000000000000000010 // 1st itteration (shifted by 1) 00000000000000000000000000000100 // 2nd itteration (shifted by 2) ... 10000000000000000000000000000000 // 31st itteration (shifted by 31) |
接下来的第32次发信号会导致整数溢出或
1 | 0000000000000000000000000000000 // 32nd itterartion, now we have 0 |
当计数器达到int.MaxValue时,计数器* 2变为负整数。
然后,当计数器达到int.MinValue时,计数器* 2变为0。
然后,在每次迭代中,您都有0 * 2 = 0,没有异常可以抛出。