Search code examples
c++floating-pointdoubleinfinitycmath

Does the cmath macro INFINITY always works for double?


I'm using the cmath macro INFINITY with double numbers and I've not seen any problem so far: in my experience it has always evaluated to double infinity. For instance:

#include <iostream>
#include <cmath>

int main()
{
    double x = INFINITY;
    std::cout << x << std::endl; // prints "inf" as expected
    return 0;
}

But according to C++ reference and cplusplus.com, INFINITY seems guaranteed to evaluates to infinity only for float. Is it always guaranteed to evaluate to infinity for double (and long double) too?

I know that the C++ standard library std::numeric_limits solves this problem but I'm working on an embedded system with limited memory so I would rather use what I already have (cmath) than add another header.

Edit: I'm using C++11.


Solution

  • Yes. Per the C++14 standard:

    1. A prvalue of type float can be converted to a prvalue of type double. The value is unchanged.

    -- N4296 [conv.fpprom]

    If the value was infinity before promotion to a double, it will remain infinity after promotion.