C++ – Range based for loop throws a compiler error with array parameter

c++visual-studio

Admittedly, I'm just finding my footsteps in C++ but I don't understand the error here.

The following error gets displayed:

Error 1 error C3312: no callable 'begin' function found for type 'int []'

Error 2 error C3312: no callable 'end' function found for type 'int []'

Error 3 error C2065: 'i' : undeclared identifier

4 IntelliSense: this range-based 'for' statement requires a suitable "begin" function and none was found

Code:

#include <iostream>

using namespace std;

void printArray(int[]);

int main() {
    int a[] = { 1, 2, 3, 4, 5 };
    printArray(a);
    system("pause");
    return 0;
}

void printArray(int a[]) {
    for (int i : a) {
        cout << i << " ";
    }
}

Can't figure out what the problem is.

Best Solution

Inside printArray, a is not an array! I know it looks like one, but it's not. int a[] there means int* a, due to a nasty legacy from the 1850s.

Here is the fix to your problem, passing in the array by reference and therefore keeping its full type (including numerical dimension):

#include <iostream>

template <size_t N>
void printArray(int (&a)[N]) {
    for (int i : a) {
        std::cout << i << " ";
    }
}

int main() {
    int a[] = { 1, 2, 3, 4, 5 };
    printArray(a);
}

(I've also removed some redundant code and that horrid system("pause"): properly configure your execution environment rather than having your program take responsibility for blocking its caller when it's finished!)

(live demo)

Related Question