Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about array parameters

Tags:

c++

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

Exercise 6.24: Explain the behavior of the following function. If there are problems in the code, explain what they are and how you might 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 problem in the codes. What is the point of this exercise?

like image 906
pezy Avatar asked Oct 23 '14 14:10

pezy


1 Answers

The general problem is that in C++ declaration syntax, array types in function parameter declarations mean something non-intuitive: 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 there are no prvalues of array type in C++, and so array types cannot be function parameter or return types. (When used as a prvalue, an array decays to a pointer to its first element.)

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

void print(const int *);

This parameter type plays well with the array-to-pointer decay, but it is now clear that you can pass any pointer to int to this function, and the correctness of the function execution cannot be determined from the function definition alone.

*) It's a bit more complicated in C99.


On a side note, array glvalues are perfectly fine, as is the following function which has a parameter whose type is "reference to array":

void print10(const int (&a)[10])
{
    for (auto i : a) { std::cout << i << "\n"; }
}
like image 96
Kerrek SB Avatar answered Nov 14 '22 21:11

Kerrek SB