Integer Literal Division Truncating To Zero
ID |
go.integer_literal_division_zero |
Severity |
low |
Remediation Complexity |
simple |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
CWE:682, reliability, suspicious |
Description
Reports a division a / b of two integer literals that truncates to 0 — for example 2 / 3.
Integer division in Go truncates toward zero, so a numerator smaller than the divisor yields a
constant 0.
Rationale
A literal integer division that evaluates to zero is almost always a mistake: the author expected a
fractional result and forgot to make one operand floating-point. The check fires only when both
operands are integer literals, the divisor is non-zero, and the quotient truncates to 0. A float
literal operand (which forces float division) or a variable operand is not flagged.
func fn() {
_ = 2 / 3 // FLAW — truncates to 0
_ = 4 / 3 // OK — equals 1
_ = 2 / 3.0 // OK — float division
}