April 25, 2020

Why can't double be automatically converted to long in static languages?

  • long takes 64 bits, of which 63 bits are assigned to a value, 1 bit (the highest) to a sign, and long takes from -2^63 to +2^63
  • double also takes 64 bits, but 52 bits are allocated to the fractional part, 11 bits to the degree (mantissa) and 1 bit to the sign - more information here, as a result, double takes from ~-1.7^308 to ~+1.7^308

As you can see, the internal structure of both types is completely different, and most importantly, the maximum values are also different.

"Automatic" caste passes if only the receiving type is "wider" than the original, for example:

long x=10; double y=x; / / works because double is "wider" long


and here is the structure:

double x=10.0; long y=x; //doesn't work anymore, because long "Already" double long z=(long )x; / / forced caste required