Why is this an issue?
When a loop variable is not used outside of a loop, it should be declared inside the loop declaration:
- It improves readability, the scope of the variable is clearly defined
- It reduces the number of mistakes, the variable can’t be accidentally misused outside of the loop
- Resources are not retained longer than necessary
Noncompliant code example
using namespace std;
void f() {
int i = 0; // Noncompliant: i is not used outside of the loop
for (i = 0; i < 10; ++i) {
cout << i << endl;
}
}
Compliant solution
using namespace std;
void f() {
for (int i = 0; i < 10; ++i) {
cout << i << endl;
}
}
Resources