CWG Issue 2220 (original) (raw)

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

2025-04-13


2220. Hiding index variable in range-based for

Section: 8.6.5 [stmt.ranged]Status: C++17Submitter: Daveed VandevoordeDate: 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 forstatement. 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 fordoes 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_]