Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Unary minus in C++

Unary minus negates one operand. In `return -1;`, it produces an `int` value that this function uses to mean “not found”; it is not subtraction.

Version: ISO C++23; implementation support may vary

Syntax

-operand
return -1;

In -x, the built-in unary minus (-) produces the negative of x without modifying the operand. In -1, 1 is the int literal and - is a separate operator. In a - b, the minus is binary: it subtracts b from a. In 4 - -1, the first minus subtracts and the second negates.

The built-in operator accepts arithmetic and unscoped enumeration types. Integral and enumeration operands undergo integral promotion first; the result has the promoted operand type. User-defined types can provide a unary operator- overload distinct from a subtraction overload.

If the promoted type is unsigned, the result is computed modulo 2^N, where N is the number of value bits in that type. Thus -1u gives the maximum unsigned int value, not negative one. Negating the minimum int value is undefined behavior because its positive counterpart cannot be represented as an int.

find_index returns a zero-based index or -1 when the item is not found. This is the function’s documented sentinel, not a special language rule. Check the result before using it as an index or converting it to an unsigned type.

Examples

#include <iostream>
#include <limits>

int find_index(int target) {
    constexpr int values[] = {4, 7, 9};
    int index = 0;
    for (int value : values) {
        if (value == target) {
            return index;
        }
        ++index;
    }
    return -1;
}

int main() {
    static_assert(-1u == std::numeric_limits<unsigned int>::max());

    std::cout << find_index(7) << '\n';
    std::cout << find_index(8) << '\n';
    std::cout << (4 - -1) << '\n';
}

Result

1
-1
5

`7` is at index `1`; `8` is absent, so the function returns `-1`. The last line is `5`. The `static_assert` checks the value of `-1u` at compile time and prints nothing.

Related lessons

  • C++ · Lesson 6 · Advanced · Version: 3

Sources