0

I want to iterate an array inside a function. the following code won't compile.

void printArr(int arr[])
{
    for (auto x : arr)
    {
        cout << x << endl;
    }
}

I know arr is actually a pointer to the first element. Thanks for helping.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Avi Harush
  • 989
  • 2
  • 10
  • 15

2 Answers2

4

The reason is that the range based loop needs an array type, a standard library container, or something with suitable begin and end iterators. In your function, arr is just a pointer (a function parameter such as int arr[] is adjusted to int* arr).

From a practical perspective, the range based loop could not know how many elements to print, so it would make no sense for it to deal with a pointer.

You could try passing the array by reference instead.

template <size_t N>
void printArr(const int (&arr)[N])
{
    for (auto x : arr)
    {
        cout << x << endl;
    }
}

Where a template function has been used to allow for arrays of different lengths. You could also make the element type a template parameter:

template <typename T, size_t N>
void printArr(const T (&arr)[N])
{
  ....
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

It is because array arguments are depleted to pointers and range based loops require an array or a container type. You can instead try the following code:

template <typename T, size_t sz>
void printArr(const T (&arr)[sz])
{
    for (auto x : arr)
    {
        cout << x << endl;
    }
}

Live demo here

This code passes the reference of array instead of address.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100