Title
Hiding index variable in range-based for
Status
c++17
Section
8.6.5 [stmt.ranged]
Submitter
Daveed Vandevoorde

Created on 2016-01-08.00:00:00 last changed 74 months ago

Messages

Date: 2017-01-15.00:00:00

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]

Date: 2017-02-15.00:00:00

[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?

History
Date User Action Args
2018-02-27 00:00:00adminsetstatus: tentatively ready -> c++17
2017-02-06 00:00:00adminsetmessages: + msg5734
2016-01-08 00:00:00admincreate