CKTIS / C++
Unary negation (`-`) in C++
Unary minus computes the negative of one operand, whereas binary subtraction computes a difference. The promoted type determines what happens at the limits of its range.
Version: ISO C++23; implementation support may vary
Syntax
-expression // unary negation
left - right // binary subtractionIn C++23, built-in unary negation (-) takes one operand: -x computes the negative of x without modifying x itself. In contrast, a - b is binary subtraction and takes two operands. In -7, the minus is an operator applied to the literal 7, not part of the literal.
Built-in unary minus accepts arithmetic and unscoped enumeration types. Integral promotions apply to integral and enumeration operands; the result has the type of the operand after any promotion. If that type is unsigned and has width N, negation is computed modulo 2 to the power of N. Thus -1u is the largest unsigned int value, not negative one. Evaluating -INT_MIN (<climits>) is undefined behavior because the result does not fit in int. Check the range before negating.
In -DBL_MAX, the operand is DBL_MAX, the macro from <cfloat> for the largest finite double. For an IEC 60559 double, the result is the finite lower bound. To get that bound without assuming this representation, use std::numeric_limits<double>::lowest() from <limits>. For double, min() instead gives the smallest positive normalized value.
For a class type, overload resolution may select a unary operator-: a non-static member function with no non-object parameters, or a non-member function with one parameter. The selected function defines the meaning of the operation; it need not follow the built-in negation rules.
Examples
#include <cfloat>
#include <iostream>
#include <limits>
int main() {
const int x = 7;
double lower = std::numeric_limits<double>::lowest();
if constexpr (std::numeric_limits<double>::is_iec559) {
lower = -DBL_MAX;
}
std::cout << "unary: " << -x << '\n'
<< "binary: " << 10 - x << '\n'
<< std::boolalpha
<< "unsigned maximum: " << (-1u == std::numeric_limits<unsigned int>::max()) << '\n'
<< "negative lower bound: " << (lower < 0.0) << '\n';
}
Result
unary: -7 binary: 3 unsigned maximum: true negative lower bound: true
The program contrasts negation with subtraction, then checks the unsigned result and whether the finite lower bound is negative. It uses `-DBL_MAX` only for an IEC 60559 `double`.
Related lessons
- C++ · Lesson 60 · Advanced · Version: 3
Sources
- Working Draft, Standard for Programming Language C++ (N4950, C++23 working draft)
- Unary operators [expr.unary.op]
- Additive operators [expr.add]
- Integer literals [lex.icon]
- Integral promotions [conv.prom]
- Fundamental types [basic.fundamental]
- Header <cfloat> synopsis [cfloat.syn]
- numeric_limits members [numeric.limits.members]
- Unary operators [over.unary]