{cpp}20 has introduced an initializer construct in the range-based ``++for++`` loops. Similar to ``++if++`` with initializer and ``++switch++`` with initializer, the initializer of a range-based ``++for++`` loop enables you to declare and initialize a variable to make it visible only in the range condition and in the body of the loop.
Previously, variables were either declared before the statement, hence leaked into the ambient scope, or an explicit scope was used to keep the scope tight, especially when using RAII objects. This was inconvenient as it would lead to error-prone patterns.
This rule reports variables declared outside and used only inside of a range-based ``++for++`` loop.
auto rows = getTable(); // Noncompliant: rows is accessible outside of the loop
for (int x : rows[0]) {
std::cout <<x <<' ';
}
// ...
}
----
Using a temporary to avoid leaking of the variable into the ambient scope creates a bigger problem: an undefined behavior. Even though the lifetime of a temporary returned by the range expression is extended, the life of a temporary within the range expression terminates before the loop begins to execute.