C++ does not require implementations to support infinity or division by zero. Many implementations will, as many implementations use IEEE 754 formats even if they do not fully support IEEE 754 semantics.
When you want to use infinity as a value (that is, you want to refer to infinity in source code), you should not generate it by dividing by zero. Instead, include <limits>
and use std::numeric_limits<T>::infinity()
with T
specified as double
.
Returns the special value "positive infinity", as represented by the floating-point type T. Only meaningful if std::numeric_limits< T >::has_infinity
== true
.
(You may also see code that includes <cmath>
and uses INFINITY
, which are inherited from C.)
When you want to check if a number is finite, include <cmath>
and use std::isfinite
. Note that computations with infinite values tend to ultimately produce NaN
s, and std::isfinite(x)
is generally more convenient than !std::isinf(x) && !std::isnan(x)
.
A final warning in case you are using unsafe compiler flags: In case you use, e.g., GCC's -ffinite-math-only
(included in -ffast-math
) then std::isfinite
does not work.