嵌套循环使用相同变量¶
ID: cpp/nested-loops-with-same-variable
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- maintainability
- correctness
Query suites:
- cpp-security-and-quality.qls
此规则查找嵌套循环,其中两个循环的迭代变量相同。循环的行为将难以理解,因为内循环将影响外循环的迭代变量;这很可能是一个拼写错误。
该规则将标记内循环中的条件表达式,该表达式使用与外循环迭代变量相同的变量。
建议¶
如果内循环从将变量初始化为 0 开始,则很可能是一个拼写错误,因此应该更改内循环变量。在嵌套循环中使用描述性的名称而不是 i 和 j 是一个好习惯,可以避免混淆。如果内循环只是作为特例消费剩余的迭代,则最好用 while 循环替换内循环 for 循环,并对其进行记录。
示例¶
int x1 = 0;
for (x1 = 0; x1 < 100; x1++) {
int x2 = 0;
for (x1 = 0; x1 < 300; x1++) {
// this is most likely a typo
// the outer loop will exit immediately
}
}
for (x1 = 0; x1 < 100; x1++) {
if(x1 == 10 && condition) {
for (; x1 < 75; x1++) {
// this should be written as a while loop
}
}
}
参考资料¶
Tutorialspoint - C++ 编程语言:C++ 嵌套循环