Confused about array parameters

This is an exercise from C ++ Primer 5th edition, which:

Exercise 6.24: Explain the behavior of the following function. If there are problems in the code, explain what they are and how you can fix them.

void print(const int ia[10]) { for (size_t i = 0; i != 10; ++i) cout << ia[i] << endl; } 

I can not find any problems in the codes. What is the meaning of this exercise?

+5
source share
1 answer

A common problem is that in C ++ declaration syntax, array types in function parameter declarations mean something unintuitive: a parameter declared as T[] or as T[10] or as T[1279] is actually declared as T* - all these parameter declarations are identical. *

Remember that in C ++ there are no array type values, therefore array types cannot be function parameters or return types. (When used as a prvalue, the array decays to a pointer to its first element.)

Therefore, your function declaration is actually (with T = const int ):

 void print(const int *); 

This type of parameter goes well with the decay of an array to a pointer, but now it’s clear that you can pass any pointer to an int on this function, and the correctness of the function cannot be determined from the function definition alone.

*) A bit more complicated on the C99.


On the side of the note, the values ​​of the gl array are excellent, as is the following function, which has a parameter whose type is an β€œarray reference”:

 void print10(const int (&a)[10]) { for (auto i : a) { std::cout << i << "\n"; } } 
+9
source

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


All Articles