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

The output of the next function is "int *", which means that the formal parameter is converted to an integer pointer. Is there a necessary reason for this design? Why can't we reserve an 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; } 
+4
source share
2 answers

Is there a necessary reason for this design?

This is historical baggage from C. Presumably 1 This was a convenience, since you cannot pass arrays -value in any case.

If you want to keep this type, you can use links or pointers:

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

Or using the template functions to receive an array of arbitrary size:

 template<std::size_t N> void Func(int (&ar)[N]); 
+7
source

I would like to add that this is called "array decay", and there is a good discussion here:

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

Using source arrays in C ++ is a bit "c-style". True C ++ adherents use std :: vector, which has no problems with decoding and typing. However, legacy code is full of raw arrays, and C ++ compilers must play by C rules to ensure compatibility.

+2
source

Source: https://habr.com/ru/post/1316253/


All Articles