anon
anon

Reputation: 83

What does "non const-qualified" mean?

I'm trying to pass an array by reference to funcA.

void funcA(int(&a)[], int k);

int main() {
    int n = 5;
    int x[5];
    funcA(x, n);
    return 0;
}

However when I try to, it throws this error.

 A reference of type "int (&)[]" (non const-qualified) cannot be initialized with a value of type "int [5]"

I tried to find what "non const-qualified" meant, but there weren't any good explanations anywhere. Can someone please explain what it means? Thank you.

Upvotes: 0

Views: 856

Answers (1)

nielsen
nielsen

Reputation: 7719

First of all, you cannot have a reference to an array of unbound size. The closest thing is a reference to a pointer (to the array), i.e. int * (&a). This still gives a problem because a is not constant and the passed parameter x is a constant (the location of the array) - this is actually what the compiler error in the question is referring to. Hence, we need a to be a reference to a constant pointer to a non-constant array, i.e.:

void funcA(int * const (&a), int k)
{
    a[k-1] = 0;  // Just a dummy example
}

int main() {
    int n = 5;
    int x[5];
    funcA(x, n);
    return 0;
}

It should be mentioned that there is no downside to using the more common form of passing an array instead:

void funcA(int *a, int k)

Upvotes: 1

Related Questions