I am trying to loop through an array inside a function called ref. But ranged-based for loop is not working here. The error message tells me-
app.cpp:7:17: error: ‘begin’ was not declared in this scope
7 | for(int i : x){
But when I am using the normal for loop, it seems to work perfectly. I don't know what's going on here. Can anyone please help me?
Here is my code-
#include <iostream>
using namespace std;
void ref(int x[]){
for(int i : x){
cout << i;
}
}
int main(int argc, char const *argv[])
{
int x[]={3,5,6};
return 0;
}
xis actuallyint*and we can't loop through anint*.ref(),xis a pointer, not an array (even though the notation can be interpreted otherwise). There is no information available to the compiler about the number of elements in the array passed (or, for that matter, about whether an array was passed at all). You need to pass the number of elements (3in this case) via another parameter, and use a non-rangeforloop (e.g.for (int i = 0; i < num; ++i) cout << x[i];). Alternatively, usestd::array<int, 3>(from standard header<array>) instead, since a range-basedforcan operate properly on astd::array.