# C++ cmath copysign , copysignf and copysignl

1 float copysign(float x , float y);
2 double copysign(double x , double y);
3 long double copysign(long double x , long double y);
4 float copysignf(float x , float y);
5 long double copysignl(long double x , long double y);

The C++ <cmath> copysign,copysignf and copysignl return the magnitude of ‘x’ but with the sign of ‘y’.

Some points to note:

i) If ‘x’ is NaN ,’nan’ is returned but with the sign of y.

ii) If x is ±∞ ,∞ is returned with the sign of ‘y’.

Code example

cout<< “copysign(23 , -9)=” << copysign(23 , -9) << endl ;

/*Passing x as ∞ */
cout<< “copysign(∞ , -9)=” << copysign(∞ , -9) << endl ;

/*Passing y as ±∞ */
cout<< “copysign(123 , -∞)=” << copysign(123 , -∞) << endl ;

Output

copysign(23 , -9)= -23
copysign(∞ , -9)= -∞
copysign(123 , -∞)= -123

#### copysignf and copysignl

i)The 4th version copysignf is same as the 1st version float copysign(float,float).The last character ‘f‘ in ‘copysignf’ stands for ‘float’ which signify the argument type and return type of the function.

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

Code example

#include <typeinfo>

/*copysignf */
cout<< “*copysignf\n”;
float f=2 , f1=78 ;
cout<< typeid( copysignf(2 , 8) ).name() << endl /*identify type of copysignf returned value */
<< typeid( copysign(f , f1) ).name() << endl; /*identify type of copysign(float , float) returned value */

/*copysignl*/
cout<< “*copysignl\n”;
long double ld=2 , ld1=90;
cout<< typeid( copysignl(2 , 90) ).name() << endl /*identify type of copysignl returned value */
<< typeid( copysign(ld , ld1) ).name() << endl; /*identify type of copysign(long double , long double) returned value*/

Output

*copysignf
f
f
*copysignl
e (means ‘long double’)
e (means ‘long double’)