# C++ cmath fabs , fabsf, fabsl function

The C++ <cmath> fabs,fabsf and fabsl function give the absolute value of the value.The declaration of the functions are given below.

fabs

1 float fabs(float x);
2 double fabs(double x);
3 long double fabs(long double x);
4 float fabsf(float x);
3 long double fabsl(long double x);

Parameters(for both abs and fabs function):
x -The floating point value.

Return type
floating point -The absolute value of ‘x’.

Some points to note:

i) The fabs function is quite fast.

ii) If NAN is passed NAN is returned.

iii) If ±∞ is passed ∞ is returned.

iv) If ±0 is passed 0 is returned.

Code example

/*Passing floating point value*/
cout<< “fabs(-9)=” << fabs(-9) << endl;

/*Passing floating point value*/
cout<< “fabs(-INFINITY)=” << fabs(-INFINITY) << endl;

/*Passing -0*/
cout<< “fabs(-0.0)=” << fabs(-0.0) << endl;

Output

fabs(-9)= 9
abs(-9)= 9
fabs(-INFINITY)= inf
abs(-INFINITY)= inf
fabs(-0.0)= 0

#### fabsf and fabsl

*Note

i)The 4th version fabsf is same as the 1st version float fabs(float) .The ‘f‘ character appended to ‘fabsf’ stands for ‘float’ which signify the argument type and return type of the function.

ii)The 5th version fabsl is same as the 3rd version long double fabs(long double).The ‘l‘ character in ‘fabsl’ stands for ‘long double’ which signify the argument type and return type of the function.

Code example

#include <typeinfo>

/*fabsf */
cout<< “*fabsf\n”;
float f=2;
cout<< typeid( fabsf(2) ).name() << endl /*identify type of fabsf retunred value */
<< typeid( fabs(f) ).name() << endl; /*identify type of fabs(float) returned value */

/*fabsl*/
cout<< “*fabsl\n”;
long double ld=2;
cout<< typeid( fabsl(2) ).name() << endl /*indentify type of fabsl returned value */
<< typeid( fabs(ld) ).name() << endl; /*identify type of fabs(long double) returned value*/

Output

*fabsf
f
f
*fabsl
e (means ‘long double’)
e (means ‘long double’)