How to Assign Negative Infinity in C++?

In C++, the infinity is written as inf. We get infinity as a result when a positive number is divided by a null value or when a value is much greater and cannot be stored in 64-bit. In C++, positive infinity is defined in many libraries but the negative infinity is not defined. In this article, we will learn how to define and use the negative infinity in C++.

Negative Infinity in C++

In C++, we can use the std::numeric_limits<T>::infinity() function from the <limits> library that returns the value of positive infinity and then we can multiply it by “-1” to make it negative. When a negative infinity is obtained it can then be used for various purposes like Initializing variables to negative infinity, comparing values, and using it as a lower bound in algorithms that require range checking, etc.

Syntax to Define Negative Infinity

dataType negInfinity = -std::numeric_limits<dataType>::infinity();

Here, dataType is a non-integral data (float or double).

C++ Program to Assign Negative Infinity to a Number

The below program demonstrates how we can define and use negative infinity in C++.

C++
// C++ program to demonstrate the use of negative infinity

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    // Defining negative infinity
    double negInfinity
        = -numeric_limits<double>::infinity();

    // Printing the value of negative infinity
    cout << "Negative Infinity: " << negInfinity << endl;

    // Using negative infinity in a comparison
    double num = -1000.0;
    if (num < negInfinity)
        cout << num << " is less than negative infinity."
             << endl;
    else
        cout << num << " is greater than negative infinity."
             << endl;

    return 0;
}

Output
Negative Infinity: -inf
-1000 is greater than negative infinity.

Time Complexity: O(1)
Auxilliary Space: O(1)

Note: The infinity() method is valid only for non-integral data types as integral data types like int and bool are inherently finite.