Unsigned Negative Comparison
ID |
go.unsigned_negative_comparison |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious-comparison |
Description
Reports a relational comparison between an unsigned-typed operand and a negative integer
literal, such as u < -1 or u >= -1.
Rationale
An unsigned integer can never hold a negative value, so a comparison against a negative
literal has a constant result: u < -1 (and u ⇐ -1, u == -1) is always false, while
u >= -1 (and u > -1, u != -1) is always true. The code reads as a real test but does
nothing — a guard that fails to reject anything, or a condition that is always taken. It is
almost always a logic error, often caused by forgetting that the variable is unsigned.
func check(u uint) {
if u < -1 { ... } // FLAW — always false
if u >= -1 { ... } // FLAW — always true
if u < 5 { ... } // OK
}
Remediation
Reconsider the intended bound. If the value should be tested for zero, compare against 0
(u == 0); if the variable can legitimately be negative, change its type to a signed integer.