C++ nexttoward()

The nexttoward() function in C++ takes two arguments and returns the next representable value after x in the direction of y.

The function is defined in <cmath> header file.

It is identical to nextafter() except that the second argument of nexttoward() is always of type long double.


nexttoward() prototype [As of C++ 11 standard]

double nexttoward(double x, long double y);
float nexttoward(float x, long float y);
long double nexttoward(long double x, long double y);
double nexttoward(T x, long double y); // For integral type

The nexttoward() function takes a two arguments and returns a value of type double, float or long double type.


nexttoward() Parameters

  • x: The base value.
  • y: The value towards which the return value is approximated.

nexttoward() Return value

The nexttoward() function returns the next representable value after x in the direction of y.


Example 1: How nexttoward() function works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    long double y = -1.0;
    double x = 0.0;
    
    double result = nexttoward(x, y);
    cout << "nexttoward(x, y) = " << result << endl;

    return 0;
}

When you run the program, the output will be:

nexttoward(x, y) = -4.94066e-324

Example 2: nexttoward() function for integral types

#include <iostream>
#include <cmath>
#include <climits>

using namespace std;

int main()
{
    long double y = INFINITY;
    int x = INT_MAX;

    double result = nexttoward(x,y);
    cout << "nexttoward(x, y) = " << result << endl;

    return 0;
}

When you run the program, the output will be:

nexttoward(x, y) = 2.14748e+09
Did you find this article helpful?