Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is for (auto& a : a) grammatically right?

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.

like image 244
user1899020 Avatar asked Jun 26 '16 19:06

user1899020


2 Answers

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
   }
}
like image 154
Ben Voigt Avatar answered Oct 19 '22 19:10

Ben Voigt


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.

like image 6
Rakete1111 Avatar answered Oct 19 '22 21:10

Rakete1111