1

In C++, arrays are supposed to be passed to functions by reference. Hence, in what follows, function foo should implicitly use array inp by reference.

void foo(double inp[10]) {}
void foo1(double (&inp)[10]) {}

My question is, since both functions supposedly have the same interpretation of the input variable, why can we call foo in what follows, but we cannot call foo1?

int main()
{
    double ary[20];
    foo(ary);  // compiles without any problem.
    foo1(ary); // compiler error: invalid initialization of reference of type ‘double (&)[10]’ from expression of type ‘double [20]’
    return 0;
}
MTMD
  • 1,162
  • 2
  • 11
  • 23

1 Answers1

3

since both functions supposedly have the same interpretation of the input variable

But they don't. A function argument of the type double inp[10] is automatically adjusted to a pointer double*. The 10 plays no part in providing type information here. Since all arrays decay to pointers, that will allow you to pass an array of any size.

A reference to an array does not get adjusted however. The type information is still there, and it must be a reference to an array of exactly ten doubles. The only way to pass a reference to an array of any size is to have a separate function for it, which you may write a function template to accomplish

template<std::size_t N>
void foo2(double (&inp)[N]) {}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458