mirror of
https://github.com/github/codeql.git
synced 2026-02-21 09:23:40 +01:00
54 lines
1.9 KiB
XML
54 lines
1.9 KiB
XML
<!DOCTYPE qhelp PUBLIC
|
|
"-//Semmle//qhelp//EN"
|
|
"qhelp.dtd">
|
|
<qhelp>
|
|
<overview>
|
|
<p>
|
|
Most <code>for</code> loops either increment a variable until an upper bound is reached,
|
|
or decrement a variable until a lower bound is reached. If, instead, the variable is
|
|
incremented but checked against a lower bound, or decremented but checked against an
|
|
upper bound, then the loop will usually either terminate immediately and never execute
|
|
its body, or it will keep iterating indefinitely. Neither is likely to be intentional,
|
|
and is most likely the result of a typo.
|
|
</p>
|
|
<p>
|
|
The only exception to this are loops whose loop variable is an unsigned integer. In this
|
|
case, initializing the variable with an upper bound and then decrementing it while
|
|
checking against the same upper bound is unproblematic: the variable is counted down
|
|
from the upper bound to zero, and then wraps around to a large positive value, causing
|
|
the loop to terminate. This is usually intentional, and hence is not flagged by the query.
|
|
</p>
|
|
|
|
</overview>
|
|
<recommendation>
|
|
|
|
<p>
|
|
Examine the loop carefully to check whether its test expression or update statement
|
|
are erroneous.
|
|
</p>
|
|
|
|
</recommendation>
|
|
<example>
|
|
|
|
<p>
|
|
In the following example, two loops are used to set all elements of a slice <code>a</code>
|
|
outside a range <code>lower</code>..<code>upper</code> to zero. However, the second loop
|
|
contains a typo: the loop variable <code>i</code> is decremented instead of incremented,
|
|
so <code>i</code> is counted downwards from <code>upper+1</code> to <code>0</code>, <code>-1</code>,
|
|
<code>-2</code> and so on.
|
|
</p>
|
|
|
|
<sample src="InconsistentLoopOrientation.go" />
|
|
|
|
<p>
|
|
To correct this issue, change the second loop to increment its loop variable instead:
|
|
</p>
|
|
|
|
<sample src="InconsistentLoopOrientationGood.go" />
|
|
|
|
</example>
|
|
<references>
|
|
<li>The Go Programming Language Specification: <a href="https://golang.org/ref/spec#For_statements">For statements</a>.</li>
|
|
</references>
|
|
</qhelp>
|