4

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;
}
1

2 Answers 2

7

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

@sbi: template<typename T, std::size_t N> void func(T (&ar)[N]) is even better. :P
& @Prasoon: People often think of templates when they need something to work with different types, but usually forget about non-type template arguments.
2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.