Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Unary minus

Unary minus, written as -expression, computes the negated value. Learn how integral promotions affect the result, how unsigned negation works, and when signed overflow is a risk.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

-expression

The operator -x has one operand, unlike subtraction a - b. Built-in unary minus computes the negated value without changing x.

It accepts arithmetic types and unscoped enumerations. Integral and enumeration operands undergo integral promotions; the result has the promoted type. Consequently, -small in the example has type int. The result is a prvalue.

If the promoted type is unsigned, negation works modulo 2^N, where N is that type's width: -0u is 0u, and -1u is the largest unsigned int value. Do not assume the result will be negative.

Negating a signed integer type's minimum value causes undefined behavior when the result cannot fit in the promoted type, as with the minimum int value. For class types, an overloaded operator- can define different behavior; the rules above describe the built-in operator.

Examples

#include <iostream>

int main() {
    int x = 7;
    signed char small = 3;
    auto negative = -small;

    static_assert(sizeof(negative) == sizeof(int));
    std::cout << -x << '\n';
    std::cout << x << '\n';
    std::cout << negative << '\n';
    std::cout << -(-x) << '\n';
}

Result

-7
7
-3
7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources