C++ nextafter()

The nextafter() 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.


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

double nextafter(double x, double y);
float nextafter(float x, float y);
long double nextafter(long double x, long double y);
Promoted nextafter(Type1 x, Type2 y); // Additional overloads

Since C++11, if any argument passed to nextafter() is long double, the return type Promoted is long double. If not, the return type Promoted is double.


nextafter() Parameters

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

nextafter() Return value

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


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

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = 0.0, y = 1.0;

    double resultInDouble = nextafter(x,y);
    cout << "nextafter(x, y) = " << resultInDouble << endl;

    return 0;
}

When you run the program, the output will be:

nextafter(x, y) = 4.94066e-324

Example 2: nextafter() function for arguments of different types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    float y = 1.0;
    double x = INFINITY;

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

    return 0;
}

When you run the program, the output will be:

nextafter(x, y) = 1.79769e+308