[Solved] Nested Range-based for loop Not working in C++17


This problem has nothing to do with nested loops.

The following code snippet is nonsense and the compiler ties itself into knots trying to understand it:

int main()  {
  std::vector<int> v = {0, 1, 2, 3, 4, 5};

  for (int i : v) {
    for (int a : i)
        std::cout << a << ' ';
  }
}

The error message thus is also nonsense. It is like feeding the compiler random characters, and the compiler coming back with “missing ;“.

In particular:

for (int i : v)
    for (int a : i)

The first line declares i as of type int. How could the second line, then, iterate over an int? int is not an array nor is it user-/library-defined.

Types that can be iterated over are arrays, and user/library defined types with a member begin()/end(), and such with a non-member free function begin()/end() in their namespace, whose begin()/end() return something iterator (or pointer) like.

gcc tried to treat it as an iterable object. It isn’t an array. It doesn’t have a member begin(). It isn’t defined in a namespace containing a non-member begin(). This makes gcc give up at that point, and output a message that it could not find the non-member begin() in a nonsense location (as int has no point of definition).

This will generate the same error:

int i;
for( int a:i );

solved Nested Range-based for loop Not working in C++17