This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 110b. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2023-01-15


2220. Hiding index variable in range-based for

Section: 8.6.5  [stmt.ranged]     Status: C++17     Submitter: Daveed Vandevoorde     Date: 2016-01-08

[Adopted at the February/March, 2017 meeting.]

Given an example like

  void f() {
    int arr[] = { 1, 2, 3 };
    for (int val : arr) {
      int val;   // Redeclares index variable
    }
  }

one might expect that the redeclaration of the index variable would be an error, as it is in the corresponding classic for statement. However, the restriction that makes the latter an error is phrased in terms of the condition nonterminal in 8.5 [stmt.select] paragraph 3, and the range-based for does not refer to condition. Should there be an explicit prohibition of such a redeclaration?

Proposed resolution (January, 2017):

Add the following as a new paragraph after 8.6 [stmt.iter] paragraph 3:

Thus after the while statement, i is no longer in scope. —end example]

If a name introduced in an init-statement or for-range-declaration is redeclared in the outermost block of the substatement, the program is ill-formed. [Example:

  void f() {
    for (int i = 0; i < 10; ++i)
      int i = 0;          // error: redeclaration
    for (int i : { 1, 2, 3 })
      int i = 1;          // error: redeclaration
  }

end example]