For example, I defined an multidimensional array
array<array<array<int, 3>, 4>, 5> a;
And I loop it
for (auto& a : a)
for (auto& a : a)
for (auto& a : a)
a = 1;
Is that right in grammar? I tested in VS2015. No compilation errors.
It's legal, and will do what you expect, but it is still a very bad idea to reuse variable names.
The C++11 ranged-for is defined as a source transformation, which puts definition of the range variable in an inner scope, and performs evaluation of the range expression outside that scope.
Section 6.5.4 says that
The range-based for statement
for ( for-range-declaration : for-range-initializer ) statement
is equivalent to
{ auto &&__range = for-range-initializer ; auto __begin = begin-expr ; auto __end = end-expr ; for ( ; __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } }
Yes, it is :)
The reason why is because the a
you declare in the for loop hides the original array a
:
for (auto& a : a)
^^^ ^^^^^^^^^
hides this 'a' (the original array)
And then, it's just the same all over again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With