Is it legal to declare a loop variable in a ranged-based for loop with the same name I use in the expression statement of the loop? I hope the example makes it clear.
#include <iostream>
#include <vector>
struct bar {
std::vector<int> nums;
};
int main()
{
bar b;
b.nums = {1, 2, 3};
for(int b : b.nums)
std::cout << b << std::endl;
}
gcc 4.8 gives an error while clang 3.2 allows it.
For what it's worth, this bug has now been fixed on gcc trunk. :)
Clang is right.
Paragraph 6.5.4/1 of the C++11 Standard defines the range-based
for
statement as follows:From the above, it is visible that variable
b
, which corresponds to thefor-range-declaration
, is declared inside a nested block statement, while the initializerrange-init
(which corresponds tob.nums
) appears in the parent scope, whereb
should resolve to the object of typebar
.From my reading of C++2011 6.5.4, your code of:
Should be converted to:
This to me means that clang is correct.