Range based for-loop on array passed to non-main function

With the array decaying into a pointer you’re losing one important piece of information: its size.

With an array reference your range based loop works:

void foo(int (&bar)[3]);

int main() {
  int bar[3] = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}

void foo(int (&bar)[3]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

or, in a generic fashion (i.e. without specifying the array size in the function signature),

template <std::size_t array_size>
void foo(int (&bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

Try it out

Leave a Comment