【发布时间】:2017-07-23 23:16:52
【问题描述】:
我对@987654322@ 类型的行为有点困惑。我理解它是64-bit integer used for positive numbers(最大值 18,446,744,073,709,551,615)。我刚开始使用它是因为我需要非常大的正数,但是对于潜在的负数有一些我不理解的奇怪行为。
ulong big = 1000000; //Perfectly legal
ulong negative = -1; //"Constant value "-1" cannot be converted to a ulong" Makes sense
//Attempt to sneak around the -1 as a constant compile-time error
int negativeInt = -1;
ulong negativeUlongFail = negativeInt; //"Cannot implicitly convert 'int' to 'ulong'.
//An explicit conversion exists (are you missing a cast?)"
//So I add casting
ulong negativeUlong = (ulong)negativeInt; //But this yields 18446744073709551615
//Try and get a negative number indirectly
ulong number = 0;
number = number - 10; //now number is 18446744073709551615 but no underflow error
发生了什么事?为什么一些下溢错误被捕获而其他错误甚至不抛出异常?我可以检测到这些吗?
我专注于通过下溢来获得负数,但在获得大于最大值和上溢的数字时,我也看到过类似的情况。
我不确定它们在技术上是错误还是异常,所以如果我使用了不正确的术语,请原谅我
【问题讨论】:
-
编译器默认开启下溢/下溢检测,运行时不开启。后者是项目设置,Project > Properties > Build tab > Advanced 按钮。打开复选框对于 Debug 配置是一个好主意。对于发布版本而言,检查并不多,检查非常昂贵。使用
checked和unchecked关键字即时覆盖这些默认值。
标签: c# integer overflow underflow ulong