0

when I run this

#include <cstdio>
#include <iostream>
using namespace std;

int len(int arr[]) {
    int size = 0;
    for (int x : arr) {
        size = size + 1;
    }
    return size;
}

int main() {
    int test[] = {4,7,13,25,79,2};
    cout << len(test);
}

it says

test.cpp: In function 'int len(int*)':
test.cpp:7:18: error: 'begin' was not declared in this scope
     for (int x : arr) {

i have been trying to fix this hours and i can not find what is wrong. why is this and how am i supposed to fix this.

farderer
  • 61
  • 4
  • 2
    `for (int x : arr)` - `arr` in the contest of function `len` is a pointer, not a concrete sequence container or definite array. Ranged-for cannot be used on such a construct. – WhozCraig Dec 19 '21 at 01:03
  • Another way to put it: within `len`, the size of `arr` is not known, so there's no way to iterate over it. – Igor Tandetnik Dec 19 '21 at 01:05
  • 1
    This is one, of many, reasons `std::array` or `std::vector` should be used. – Retired Ninja Dec 19 '21 at 01:05
  • You'll need to pass in the size of the array to the `len` function, so it can properly calculate the size of the array. – Eljay Dec 19 '21 at 01:25

1 Answers1

0

Ranged-based for loops have some requirements for the things they are able to iterate over.

cppreference - Range-based for loop says,

range-expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.

arr decays to a pointer and this does not apply to pointers.

Brady Dean
  • 3,378
  • 5
  • 24
  • 50