Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was the array type of formal parameter of a function converted to pointer?

Tags:

c++

The output of the following function is "int *", which means the formal parameter is converted to a integer pointer. Is there any necessary reason for this design? Why can't we reserve the array type?

// the output is "int *"
#include<typeinfo>
void Func(int ar[5])
{
  printf("%s\n", typeid(ar).name();
}
int main()
{
  int ar[5];
  Func(ar);
  return 0;
}
like image 205
Thomson Avatar asked Jan 22 '23 17:01

Thomson


1 Answers

Is there any necessary reason for this design?

This is historical baggage from C. Supposedly 1 this was convenience as you can't pass arrays by-value anyway.

If you want to preserve the type, you can use a references or pointers:

void Func(int (&ar)[5]);

Or using template functions to accept an arbitrarily sized array:

template<std::size_t N> void Func(int (&ar)[N]);
like image 100
Georg Fritzsche Avatar answered Jan 24 '23 06:01

Georg Fritzsche