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;
}
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Sonet Adhikary
  • 466
  • 1
  • 4
  • 8
  • The type of parameter `x` is actually `int*` and we can't loop through an `int*`. – Jason Jul 11 '22 at 04:08
  • In function parameters, arrays are automatically replaced by pointers. A pointer doesn't know the number of elements it points to. – HolyBlackCat Jul 11 '22 at 04:08
  • 1
    pass a vector instead – pm100 Jul 11 '22 at 04: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` (from standard header ``) instead, since a range-based `for` can operate properly on a `std::array`. – Peter Jul 11 '22 at 04:14
  • 1
    Dont rely on "C" style array passing, Use std::array or std::vector. – Pepijn Kramer Jul 11 '22 at 04:17
  • If you pass the array it decays to a pointer; If you pass a reference to the array then it stays an array. The downside is that the declaration needs the size to be a complete type. Change `void ref(int x[]){` to `void ref(int (&x)[3]){` to make it work. If you absolutely have to pass any size array by reference you need a template. The downside is that you end up with a copy of the function for every size array. Change `void ref(int (&x)[3]){` to `template void ref(int (&x)[N]){` to make it work. But normally people just pass the size or use a `std::vector`/`std::array`. – Jerry Jeremiah Jul 11 '22 at 04:32

0 Answers0