C++ isinf() function | check if given argument infinite
C++ provides us with a built-in function isinf() that helps us determine whether a given argument is infinite or not. We will see some examples that explain the working of this function further in this tutorial.
C++ isinf() function is defined in <cmath> header. To read more on <cmath> functions, see this: Mathematical functions in C++.
The syntax for isinf() is as follows:
bool isinf( float number); bool isinf( double number); bool isinf( long double number);
As you can see, the isinf() function takes a floating-point value as an input parameter. The return type for the function is bool. If the input number is infinite( positive or negative) it returns true i. e. 1 else it returns false i. e. 0.
Let’s understand it with a few examples.
In the given example, we will see what happens when an infinite number is passed as an argument in the function. See the code below.
#include <iostream> #include <cmath> using namespace std; int main() { float number = 4.0/0.0; if(isinf(number)) { cout << "Number is infinite" << endl; } else { cout << "Number is not infinite" << endl; } return 0; }
The output for the above code is:
Number is infinite
In the above example, we have passed a number (4.0/0.0) as an argument for isinf() function. Since 4.0/0.0 results in infinity, the function returns 1. Therefore, the output print “Number is infinite”.
Now have a look at the below code where we have passed a finite number as input.
#include <iostream> #include <cmath> using namespace std; int main() { float number = -4.0; if(isinf(number)) { cout << "Number is infinite" << endl; } else { cout << "Number is not infinite" << endl; } return 0; }
Output:
Number is not infinite
As you can see, for a non-infinite number the isinf() function returns 0.
Thank you.
Also read: C++ Math nexttoward() function with example
Leave a Reply