In C++, std::signbit(x) tells you whether a decimal number is negative. It reads the sign bit stored inside the number, and returns true if that bit is set.
This is different from x < 0. Negative zero (-0.0) is not less than zero, but its sign bit is set, so signbit() says true. The function also gives the sign of infinity and NaN.
std::signbit() 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::signbit. Start with these lines.
C++
bool a = std::signbit(-2.5); // true
bool b = std::signbit(3.0); // false
bool c = std::signbit(-0.0); // true
Call
What it does
std::signbit(-2.5)
The number is negative. Returns true.
std::signbit(3.0)
The number is positive. Returns false.
std::signbit(-0.0)
Negative zero has its sign bit set. Returns true.
Print the result with std::boolalpha to see true or false instead of 1 or 0.
For -1.5 the two checks agree. Both a < 0 and signbit(a) print 1.
For -0.0 the less-than test prints 0, because negative zero is equal to zero, not smaller than it.
signbit(b) still prints 1. Choose signbit() when you need to know about the sign itself, and not just about the size.
Example 3 — Label Changes as Falling or Rising
A list of daily changes: use signbit() to label each one as falling or not falling.
C++
#include <cmath>
#include <iostream>
int main() {
double change[] = {-1.5, 0.0, 2.0, -7.25};
for (double c : change) {
const char* label = std::signbit(c) ? "falling" : "steady or rising";
std::cout << c << ": " << label << '\n';
}
return 0;
}
Output
-1.5: falling
0: steady or rising
2: steady or rising
-7.25: falling
How It Works
Each change is tested with std::signbit(c). The conditional operator chooses one of two text labels.
-1.5 and -7.25 are negative, so they get the label falling.
0.0 and 2.0 have no sign bit. They are not falling, so they print steady or rising.
Frequently Asked Questions
std::signbit(x) returns true if the sign of x is negative, and false if it is positive. It also works for -0.0 and for NaN values.
A bool. true if the sign bit is set (negative), false otherwise.
Not exactly. They agree for normal numbers, but -0.0 < 0 is false while signbit(-0.0) is true. signbit() also works on infinity and NaN.
It returns a bool. Use std::boolalpha when you print it if you want the words true and false.
Include <cmath> and write std::signbit(). That always works and picks the C++ overloads. The global name ::signbit often works too, but the standard does not promise it, and it may only take a double.