Expressions and statements
ES.6
Declare names in for-statement initializers and conditions to limit scope
Reason
Readability. Limit the loop variable visibility to the scope of the loop. Avoid using the loop variable for other purposes after the loop. Minimize resource retention.
Example
void use()
{
for (string s; cin >> s;)
v.push_back(s);
for (int i = 0; i < 20; ++i) { // good: i is local to for-loop
// ...
}
if (auto pc = dynamic_cast<Circle*>(ps)) { // good: pc is local to if-statement
// ... deal with Circle ...
}
else {
// ... handle error ...
}
}
Example, don't
int j; // BAD: j is visible outside the loop
for (j = 0; j < 100; ++j) {
// ...
}
// j is still visible here and isn't needed
See also: Don't use a variable for two unrelated purposes
Enforcement
- Warn when a variable modified inside the
for-statement is declared outside the loop and not being used outside the loop. - (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
Discussion: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
C++17 and C++20 example
Note: C++17 and C++20 also add if, switch, and range-for initializer statements. These require C++17 and C++20 support.
map<int, string> mymap;
if (auto result = mymap.insert(value); result.second) {
// insert succeeded, and result is valid for this block
use(result.first); // ok
// ...
} // result is destroyed here
C++17 and C++20 enforcement (if using a C++17 or C++20 compiler)
- Flag selection/loop variables declared before the body and not used after the body
- (hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.