Why doesn't this verified calculation throw an OverflowException?

Can someone explain the following behavior:

    static void Main(string[] args)
    {
        checked
        {
            double d = -1d + long.MinValue; //this resolves at runtime to -9223372036854780000.00
            //long obviousOverflow = -9223372036854780000; //compile time error, '-' cannot be applied to operand of tpye ulong -> this makes it obvious that -9223372036854780000 overflows a long.
            double one = 1;
            long lMax = (long)(one + long.MaxValue); // THROWS
            long lMin = (long)(-one  + long.MinValue); // THEN WHY DOES THIS NOT THROW?
        }
    }

I do not understand why I am not getting OverFlowExceptionthe last line of code.

UPDATE Updated code to make it obvious, which is checked when you execute double and long, except in the last case.

+4
source share
3 answers

You calculate the values double( -1d). Floating-point numbers are not thrown away on .NET. checkeddoes not affect them in any way.

long checked. one + long.MaxValue double. -one + long.MinValue . , , . long.MinValue . , .

:

Debug.Assert((double)(1d + long.MaxValue) == (double)(0d + long.MaxValue));
Debug.Assert((double)(-1d + long.MinValue) == (double)(-0d + long.MinValue));

, , , double . double 2 ^ 53. . . , :

var min = (long)(double)(long.MinValue); //does not overflow
var max = (long)(double)(long.MaxValue); //overflows (compiler error)

- . .

+1

-, . :

checked {
    double longMinValue = long.MinValue;

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

Works for 1024 => -9223372036854775808 OverflowException, -9223372036854775808 i.

, .

, :

, . , . OverflowException , .

, , .

0

, :

, OverFlowException .

( 1d , , , - double):

var max = (long)(double)long.MaxValue;

, ( spec, , "" ) int64.MaxValue int64, .

var min = (long)(double)long.MinValue;

, , int64.MinValue 0, int64.

, , , .., , . , - checked, .

BitConverter.GetBytes(), , , double long , decimal double :) ( , btw, , double)

0

All Articles