Why does this checked calculation not throw OverflowException?

前端 未结 3 464
长情又很酷
长情又很酷 2020-12-21 04:31

Can somebody please explain the following behavior:

    static void Main(string[] args)
    {
        checked
        {
            double d = -1d + long.Min         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-21 05:01

    Apparently there is some leeway in the conversion from double to long. If we run the following code:

    checked {
        double longMinValue = long.MinValue;
    
        var i = 0;
        while (true)
        {
            long test = (long)(longMinValue - i);
            Console.WriteLine("Works for " + i++.ToString() + " => " + test.ToString());
        }
    }
    

    It goes up to Works for 1024 => -9223372036854775808 before failing with an OverflowException, with the -9223372036854775808 value never changing for i.

    If we run the code unchecked, no exception is thrown.

    This behavior is not coherent with the documentation on explicit numeric conversions that says:

    When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

    But as the example shows, the truncation doesn't occur immediately.

提交回复
热议问题