0

When I wrote the following code, instead of causing runtime error, it outputs 'inf'. Now, is there any way to assign this value ('inf') to a variable, like regular numeric values? How to check if a division yields 'inf'?

#include<iostream>    

int main(){
    double a = 1, b = 0;
    std::cout << a / b << endl;
    return 0;
}
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
  • 3
    Possible duplicate of [The behaviour of floating point division by zero](https://stackoverflow.com/questions/42926763/the-behaviour-of-floating-point-division-by-zero) – lubgr Aug 07 '18 at 07:56
  • 1
    Perhaps [HUGE_VAL](https://en.cppreference.com/w/cpp/numeric/math/HUGE_VAL)? – chux - Reinstate Monica Aug 09 '18 at 15:26

2 Answers2

3

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 NaNs, 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.

Julius
  • 1,816
  • 10
  • 14
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

It appears to be I can:

#include<iostream>

int main(){
    double a = 1, b = 0, c = 1/0.0;
    std::cout << a / b << endl;
    if (a / b == c) std::cout << "Yes you can.\n";

    return 0;
}
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36