0

I am trying to print values of array in called function using foreach loop but facing compilation error. Using c++11 compiler in linux platform and using VIM editor.

Tried using C-style for loop and it worked, when the size is passed from calling function

#include <iostream>
using namespace std;

void call(int [], int);

int main()
{
    int arr[] = {1,2,3,4,5};
    int size = sizeof(arr)/sizeof(arr[0]);
    call(arr,size);
}

void call(int a[],int size)
{    
    for(int i =0 ; i<size; i++)
        cout << a[i];
}

For-each loop used in the below code, which fails to compile.

#include <iostream>
using namespace std;

void call(int []);

int main()
{
    int arr[] = {1,2,3,4,5};
    call(arr);
}

void call(int a[])
{
    for ( int x : a ) 
        cout << x << endl;
}

For-each loop in C++11 expects to know the size of array to iterate ? If so, how it will be helpful with respect to traditional for loop. Or something wrong i coded here?

I would look forward for your help. Thanks in advance.

Vishwas
  • 25
  • 5
  • I'm sure someone will come with a suitable duplicate sooner or later. Until then, when used as an argument `int a[]` will be treated as `int* a`, and passing the array will make it *decay* to a pointer to its first element (i.e. you pass `&arr[0]`). That is, all you have is a pointer to the first element. – Some programmer dude Apr 29 '19 at 13:59
  • 1
    `std::vector` is your go to for these kinds of things. You may consider `std::array`. What you probably do not want is a C-style array, since it doesn't provide the nice things that you get with C++ such as supporting C++ for-each loop. – Eljay Apr 29 '19 at 14:10
  • Thanks Ejay, my question was specific to for-each loop in c++11. – Vishwas Apr 29 '19 at 14:13

1 Answers1

5

Because int a[] as function parameter is not an array, it is the same as writing int *a.

You can pass the array by reference to make it work:

template <size_t N> void call(int (&a)[N])

working example: https://ideone.com/ZlEMHC

template <size_t N> void call(int (&a)[N])
{
    for ( int x : a ) 
        cout << x << endl;
}

int main()
{
    int arr[] = {1,2,3,4,5};
    call(arr);
}
mch
  • 9,424
  • 2
  • 28
  • 42