This question already has an answer here:
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.
Aucun commentaire:
Enregistrer un commentaire