0

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;
}
6
  • The type of parameter x is actually int* and we can't loop through an int*. Commented Jul 11, 2022 at 4:08
  • In function parameters, arrays are automatically replaced by pointers. A pointer doesn't know the number of elements it points to. Commented Jul 11, 2022 at 4:08
  • 1
    pass a vector instead Commented Jul 11, 2022 at 4:12
  • Within ref(), x is 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 (3 in this case) via another parameter, and use a non-range for loop (e.g. for (int i = 0; i < num; ++i) cout << x[i];). Alternatively, use std::array<int, 3> (from standard header <array>) instead, since a range-based for can operate properly on a std::array. Commented Jul 11, 2022 at 4:14
  • 1
    Dont rely on "C" style array passing, Use std::array or std::vector. Commented Jul 11, 2022 at 4:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.