To answer your first question literally, “Why is this true?”, it is because the code if (num > DBL_MAX * 0.1)
causes program control not to go to the code that incorporates the current digit into the accumulating value.
The reason why the code is written this way is the author likely found it easier to stop processing digits than to design and implement a completely correct conversion routine. This code reads digits and builds a value from them in num
. E.g., if the input is “1234”, the code will set num to 1, then to 12 (1•10+2), then to 123 (12•10+3), and then to 1234 (123•10+4). If the input contains so many digits that the maximum finite value of a double
is approached, then it is not safe to continue this process, as the arithmetic could overflow the maximum finite value of a double. Instead, the program merely counts digits (by incrementing its exponent
) so that it may adjust for them later.
Even if there are so many digits that they would, by themselves, overflow the maximum finite value of a double, the final value might not overflow because there may be a negative exponent. E.g., you could have a thousand decimal digits followed by “e-1000”, and they would, together, represent a number less than one.
This code allows rounding in floating-point operations to affect its results and should not be used when correctly rounded conversions are desired from decimal to double
are desired.