Range based for loop in function which passes an array as value [duplicate]

The reason it doesn’t compile is that in C++ a function parameter such as char array[] is adjusted to char* array. Your function really looks like

int print_a(char* array)
{
 ....
}

and the range based loops cannot deal with a pointer.

One solution is to pass the array by reference. C++ does not allow you to pass plain arrays by value. For example, this would accept an array of 5 chars:

int print_a(const char (& array)[5])
{
   for(char c : array) cout << c;
   cout << endl;
   return 42;
}

In order to generalise this to arrays of different sizes, you can use a template:

template <std::size_t N>
int print_a(const char (& array)[N])
{
   for(char c : array) cout << c;
   cout << endl;
   return 42;
}

Of course, there are easier ways to print a null-terminated string:

char hello[] {"Hello!"};
cout << hello << endl;

And there are standard library types that make passing string or char buffer objects around easier. For example, std::string, std::vector<char>, std::array<char, N> (where N is a compile time constant.)

Leave a Comment