Home > Net >  Call Parameter as Reference to Array of Unknown Bound in C
Call Parameter as Reference to Array of Unknown Bound in C

Time:09-17

I am trying to understand whether references to array of unknown bound can be used as call parameter in functions in C . Below is the example that i have:

EXAMPLE 1

void func(int (&a)[])
{
}
int main()
{
   cout << "Hello World" << endl; 
   int k[] = {1,2,3};
  // k[0] = 3;
   func(k);
   return 0;
}

To my surprise this example 1 above works when compiled with GCC 10.1.0 and C 11 but doesn't work with GCC version lower that 10.x. I don't think that we can have references to arrays of unknown size in C . But then how does this code compile at the following link: successfully compiled

My second question is that can we do this for a function template? For example,

EXAMPLE 2

template<typename T1>
void foo(int (&x0)[])
{
}

Is example 2 valid C code in any version like C 17 etc. I saw usage of example 2 in a book where they have int (&x0)[] as a function parameter of a template function.

CodePudding user response:

I don't think that we can have references to arrays of unknown size in C .

That used to be the case, although it was considered to be a language defect. It has been allowed since C 17.

Note that implicit conversion from array of known bound to array of unknown bound - which is what you do in main of example 1 - wasn't allowed until C 20.

Is example 2 valid C code in any version like C 17

Yes; the template has no effect on whether you can have a reference to array of unknown bound.

  • Related