开发者

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

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>
v开发者_如何学Pythonoid Func(int ar[5])
{
  printf("%s\n", typeid(ar).name();
}
int main()
{
  int ar[5];
  Func(ar);
  return 0;
}


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]);


I'd like to add that this is called "the array decay" and there is a good discussion of it here:

http://www.lysator.liu.se/c/c-faq/c-2.html

Using raw arrays in c++ is a little "c-style". True C++ adepts use std::vector, which has no decay and typing problems. Nevertheless, legacy code is full of raw arrays and "C++" compilers have to play under the "C" rules to provide compatibility.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜