Identical operands¶
ID: go/redundant-operationKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctness - external/cwe/cwe-480 - external/cwe/cwe-561Query suites: - go-security-and-quality.qls
Click to see the query in the CodeQL repository
Many arithmetic or logical operators yield a trivial result when applied to identical operands: for instance,x-x is zero ifx is a number, andNaN otherwise;x&x is always equal tox. Code like this is often the result of a typo, such as misspelling a variable name.
Recommendation¶
Carefully inspect the expression to ensure it is not a symptom of a bug.
Example¶
In the example below, the functionavg is intended to compute the average of two numbersx andy. However, the programmer accidentally usedx twice, so the function just returnsx:
packagemainfuncavg(x,yfloat64)float64{return(x+x)/2}
This problem can be fixed by correcting the typo:
packagemainfuncavgGood(x,yfloat64)float64{return(x+y)/2}