In C++, std::copysign(x, y) builds a number from two parts. The size comes from x and the sign comes from y. So copysign(5.0, -1.0) is -5 and copysign(-5.0, 2.0) is 5.
Only the sign of y matters. Its size is ignored. This makes copysign() handy when you want to move in a direction without writing an if, and it can also see the sign of negative zero.
std::copysign() is declared in <cmath> and is part of the group Absolute value and sign. These functions work with the sign of a number. abs() and fabs() remove a minus sign, and copysign() and signbit() copy or read it.
Syntax
Include <cmath> and call std::copysign. Start with these lines.
C++
double a = std::copysign(5.0, -1.0); // -5
double b = std::copysign(-5.0, 2.0); // 5
float c = std::copysign(2.5f, -3.0f); // -2.5f
Call
What it does
std::copysign(5.0, -1.0)
Size of 5.0 with the sign of -1.0. Returns -5.
std::copysign(-5.0, 2.0)
The sign of y is positive, so the result is 5.
std::copysign(3.0, -0.0)
Negative zero counts as a negative sign. Returns -3.
Write std::copysign so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float copysign(float x, float y);
double copysign(double x, double y);
long double copysign(long double x, long double y);
// plus overloads for mixed and integer arguments
Parameters
Parameter
Description
x
Required. The number that gives the size (magnitude) of the result.
y
Required. The number that gives the sign of the result. Only its sign is used.
Return Value
Return Value
Description
Value with y's sign
The magnitude of x and the sign of y.
NaN
If x is NaN, the result is NaN, but it takes the sign of y.
C++ Examples
Example 1 — Basic copysign()
Give a size and a sign from two different numbers, and watch which one decides what.
z < 0: 0
z == 0: 1
copysign(1.0, z) = -1
copysign(1.0, 0.0) = 1
How It Works
-0.0 is not less than zero, so z < 0 prints 0. A normal comparison cannot see the sign here.
z == 0 is true, because -0.0 and 0.0 compare equal. That is why the sign needs another tool.
copysign(1.0, z) looks at the sign bit and returns -1, while copysign(1.0, 0.0) returns 1. This is the quick way to tell them apart.
Frequently Asked Questions
std::copysign(x, y) returns a number with the size (magnitude) of x and the sign of y.
A value with the magnitude of x and the sign of y. The sign of y is used even when y is -0.0.
No. Only the sign of y is used. copysign(5.0, -100.0) and copysign(5.0, -0.1) both return -5.
You can, but copysign() is shorter, and it also handles -0.0 and NaN signs correctly, which a comparison like y < 0 does not.
Include <cmath> and write std::copysign(). That always works and picks the C++ overloads. The global name ::copysign often works too, but the standard does not promise it, and it may only take a double.