C++ copysign()

The copysign() function in C++ takes two arguments and returns a value with the magnitude of first argument and sign of second argument.

The function is defined in <cmath> header file.


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

double copysign(double x, double y);
float copysign(float x, float y);
long double copysign(long double x, long double y);
Promoted copysign(Type1 x, Type2 y); // Additional overloads for arithmetic types

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


copysign() Parameters

  • x: Value with the magnitude of the resulting value.

  • y: Value with the sign of the resulting value.


copysign() Return value

The copysign() function returns value with the magnitude of x and the sign of y.


Example 1: copysign() function for arguments of same type

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = 34.15, y = -13.0, result;
    
    result = copysign(x, y);
    cout << "copysign(" << x << "," << y << ") = " << result << endl;
    
    return 0;
}

When you run the program, the output will be:

copysign(34.15,-13) = -34.15

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

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = 34.15, result;

    int y = -54;

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

    return 0;
}

When you run the program, the output will be:

copysign(34.15,-54) = -34.15