Unary minus applied to an unsigned operand

ID

c.correctness.unary_minus_on_unsigned

Severity

low

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

low

Resource

Numeric Operation

Language

C / C++

Description

Negating an unsigned value does not produce a negative number: the result wraps around to a very large positive one. Code that reads as a subtraction or a sign flip therefore computes something entirely different. Convert to a signed type of sufficient width before negating, or restructure the expression so the subtraction happens in the right order.

Rationale

Negating an unsigned value does not produce a negative number: the result wraps around to a very large positive one. Code that reads as a subtraction or a sign flip therefore computes something entirely different. Convert to a signed type of sufficient width before negating, or restructure the expression so the subtraction happens in the right order.

The following code illustrates the pattern detected by this rule:

void report(unsigned int count, int delta)
{
    // FLAGGED: Unary minus applied to an unsigned operand
    unsigned int wrapped = -count;

    int negated = -delta;

    printf("%u %d\n", wrapped, negated);
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

References

© 2026 Xygeni. All rights reserved