With input of “2”, your program adds two infinities of opposite signs, which generates a NaN. This occurs because repeatedly multiplying pow
by two causes it to become infinity, and the alternating sign
results in a positive infinity being added to a negative infinity in sum
from the previous iteration or vice-versa.
However, it is not clear why you see any output, as counter++
becomes ineffective once counter reaches 253 (in typical C++ implementations) because then the double
format lacks precision to represent 253+1, so the result of adding one to 253 is rounded to 253. So counter
stops changing, and the loop continues forever.
One possibility is that your compiler is generating code that always terminates the loop, because this is allowed by the “Forward progress” clause (4.7.2 in draft n4659) of the C++ standard. It says the compiler can assume your loop will not continue forever without doing something useful (like writing output or calling exit
), and that allows the compiler to generate code that exits the loop even though it would otherwise continue forever with input of “2”.
Per the IEEE-754 standard, operations that produce NaN as a result include:
- operations on a NaN,
- multiplication of zero by an infinity,
- subtraction of two infinities of the same sign or addition of two infinities of opposite signs,
- division of zero by zero or an infinity by an infinity,
- remainder when the divisor is zero or the dividend is infinity,
- square root of a value less than zero,
- various exceptions in some utility and mathematical routines (such as
pow
, see IEEE-754 9.2, 5.3.2, and 5.3.3).
C++ implementations do not always conform to IEEE-754, but these are generally good guidelines for sources of NaNs.