CodeQL documentation

Inconsistent direction of for loop

ID: cpp/inconsistent-loop-direction
Kind: problem
Severity: error
Precision: high
   - correctness
   - external/cwe/cwe-835
   - external/microsoft/6293
Query suites:
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

A for-loop iteration expression goes backwards with respect of the initialization statement and condition expression.

This warning indicates that a for-loop might not function as intended.


To fix this issue, check that the loop condition is correct and change the iteration expression to match.


In the following example, the initialization statement (i = 0) and the condition expression (i < 100) indicate that the intended iteration expression should have been incrementing, but instead a postfix decrement operator is used (i--).

void f()
    for (signed char i = 0; i < 100; i--)
        // code ...

To fix this issue, change the iteration expression to match the direction of the initialization statement and the condition expression: i++.