← 返回首页
For loop variable changed in body — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

For loop variable changed in body

ID: cpp/loop-variable-changed Kind: problem Security severity: Severity: recommendation Precision: high Tags: - reliability - readability - external/jsf Query suites: - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds for loop variables that are being modified in the loop body. for loops should be reserved for simple iteration, use while loops for more complicated cases. Most developers assume that the for loop iteration statement is the only thing that changes the value of the loop counter, so changing it inside the loop body can lead to confusion.

Recommendation

Use only the increment expression in the for loop to modify loop variables, or change it to a while loop if the loop requires more complicated variable iteration.

Example

void f() { int i = 0; for (i = 0; i < 10; i++) { //... if (special_case) { i += 5; //Wrong: loop variable changed in body, which is contrary //to the usual expectation of for loop behavior. //Use a while loop instead. continue; } } }

References