Range based for-loop on array passed to non-main function
For a fixed size array you can
Pass a raw array by reference.
Pass a
std::array
by reference.Pass a
std::vector
by reference.
The natural choice (for a fixed size array) is std::array
, i.e.
#include <iostream>
#include <array>
using namespace std;
void foo(array<int, 3> const& bar) {
for (int i : bar) {
cout << i << endl;
}
}
int main() {
array<int,3> const bar = {1,2,3};
for (int i : bar) {
cout << i << endl;
}
foo(bar);
}
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