ldexp() function in C/C++


Here we will see what is the use of ldexp() method in C or C++. This function returns any variable x raise to the power of exp value. This takes two arguments x and exp.

The syntax is like below.

float ldexp (float x, int exp)
double ldexp (double x, int exp)
long double ldexp (long double x, int exp)
double ldexp (T x, int exp)

Now let us see one example to get a better idea.

Example

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double a = 10, res;
   int exp = 2;
   res = ldexp(a, exp); // Finds a*(2^exp)
   cout << "The result is = " << res << endl;
}

Output

The result is = 40

Now let us see some errors that can be generated from this function. If the return value is too large to represent then this function will return HUGE_VAL.

Let us see the example.

Example

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double a = 10, res;
   int exp = 5000;
   res = ldexp(a, exp); // Finds a*(2^exp)
   cout << "The result is = " << res << endl;
}

Output

The result is = inf

Updated on: 30-Jul-2019

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements