CKTIS / C
copysign — C23 mathematical function
`copysign(x, y)` from `<math.h>` returns a value with the magnitude of `x` and the sign of `y`; when `x` is NaN, the result is a NaN with `y`’s sign. C23 says that if either value is unsigned, the result’s sign, if any, is implementation-defined.
Version: C23
Syntax
double copysign(double x, double y);copysign(x, y) from <math.h> returns a value with the magnitude of x and the sign of y; when x is NaN, the result is a NaN with y’s sign. C23 says that if either value is unsigned, the result’s sign, if any, is implementation-defined.
The example transfers the sign of -0.0 to 3.5, producing -3.5, and the sign of -1.0 to zero. Output -3.5 1 uses signbit to expose negative zero, which ordinary comparison with zero cannot distinguish.
Do not replace this function with multiplication: the sign bit matters for zero and NaN too. An implementation with signed zero but inconsistent negative-zero arithmetic should regard zero’s sign as positive; under Annex F/IEC 60559 the function raises no exceptions even for a signaling NaN and is independent of rounding mode.
Examples
#include <math.h>
#include <stdio.h>
int main(void) {
double changed = copysign(3.5, -0.0);
double negative_zero = copysign(0.0, -1.0);
printf("%.1f %d\n", changed, signbit(negative_zero) != 0);
return 0;
}
Result
-3.5 1
The example transfers the sign of `-0.0` to `3.5`, producing `-3.5`, and the sign of `-1.0` to zero. Output `-3.5 1` uses `signbit` to expose negative zero, which ordinary comparison with zero cannot distinguish.