How to access elements of an array from a function

  arguments, arrays, c++, for-loop, foreach

The foreach loop type doesn’t work if the array being iterated has come from a parameter and was declared in another scope.

// C++ program to demonstrate use of foreach 

#include <iostream> 
using namespace std; 
void display(int arr[])
{
    for (int x : arr) 
        cout << x << endl; 
}
int main() 
{ 
    int arr[] = { 10, 20, 30, 40 }; 
    display(arr);
} 

Here’s what the error looks like:

Here's what the error looks like

What are begin and end?
What is happening behind the scenes that gives this error?
Is the for loop implicitly changed to an iterator declaration before running? is this because C style arrays are not container objects and therefore don’t have begin and end? If this is true then why does this code work:

#include <iostream> 
using namespace std;
int main() 
{ 
    int arr[] = { 10, 20, 30, 40 }; 
    for (int x : arr) 
        cout << x << endl;
} 

Is there some information decaying happening when passed as an argument?

Source: Windows Questions C++

LEAVE A COMMENT