3

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.

8
  • 2
    Not sure what your template adds... Did you mean template<typename T>void foo(T(&a)[]) or template<size_t N> void foo(int (&a)[N])? Commented Sep 6, 2021 at 7:52
  • Using typeid(a) I can see that a is just that, an array of unknown bound. Not a pointer, nor a fancy auto-makes-template thing. Interesting... but hardly useful. Commented Sep 6, 2021 at 7:54
  • @Jarod42 It doesn't add anything. Instead the user will explicitly provide the template argument. The point being that is the usage of reference to array of unknown bound legal in C++ whether in nontemplate or template functions. It is just an example. You can remove the type parameter if you like. Commented Sep 6, 2021 at 7:56
  • gcc is rather lax with default settings. Try -pedantic-errors: wandbox.org/permlink/RVCutmkxYc18Mvyd Commented Sep 6, 2021 at 7:58
  • @463035818_is_not_a_number But the program you sent the link to works with C++2a. Commented Sep 6, 2021 at 8:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When you said that "implicit conversion from array of know bound to array of unknow bound", are you talking about the statement int k[] = {1,2,3}; or the statement ` func(k);`? I think that you mean the latter but i want to confirm.
@AanchalSharma I mean the latter. In the former, the type is adjusted to array of known bound.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.