#include <math.h>
void main() {
double a = 0;
a += 5e308;
a -= 3.5e308;
if (a == INFINITY) {
printf("1 %e\n", a);
}
else
printf("0 %e\n", a);
}
Here, the first print line is what I expect but why is the second print statement executed?
I think a
should be positive infinity as infinity -3.5e308 should be positive infinity, right in line 4?
I have already tried to execute it but the output is:
0 -1.#IND00e+000
I would like to know where my logic goes wrong.
The incorrect assumption that you seem to have is that (double) INFINITY - 3.5e308
would result in positive infinity.
Since 3.5e308
exceeds the range of double
, it is a floating-point infinity. Both GCC and Clang, with no added compiler flags, provide a warning that both of those large values are too large for the type double
.
The result is then effectively:
double a = (double) 0 + (double) INFINITY - (double) INFINITY;
It doesn't matter that, numerically, 3.5e308 is smaller than 5e308. Both are a double-precision infinity.
The subtraction of infinity from infinity is defined to result in a NaN.