== Why is this an issue?

{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.


=== Noncompliant code example

[source,cpp]
----
std::vector<std::vector<int>> getTable();
void printHeadersBad() {
  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.

[source,cpp]
----
std::vector<std::vector<int>> getTable();
void printHeadersWorse() {
  for (int x : getTable()[0]) { // Noncompliant: undefined behavior: return value of getTable() no longer exists in the loop body
    std::cout <<x <<' ';
  }
  // ...
}
----


=== Compliant solution

[source,cpp]
----
std::vector<std::vector<int>> getTable();
void printHeadersGood() {
  for (auto rows = getTable(); int x : table[0]) { // Compliant: rows is accessible only inside the loop
    std::cout <<x <<' ';
  }
  // ...
}
----


== Resources

* The same rule for ``++if++`` and ``++switch++`` statements in {cpp}17: S6004


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

=== on 24 Mar 2021, 20:37:51 Abbas Sabra wrote:
Note: To be deleted

endif::env-github,rspecator-view[]
