Reputation: 51
I understand the implicit conversion into a pointer. Someone suggested something like this today in some other question:
#include <iostream>
void printArray(int (&a)[5]) {
for (int i : a) {
std::cout << i << " ";
}
}
int main() {
int a[] = { 1, 2, 3, 4, 5 };
printArray(a);
}
Is this the only and the best way of passing an entire array to a function rather than just the pointer to the first element (though inefficient)?
However, if that function were to be written below the main function, what would the function prototype be?
Also, if I were to only use an enhanced for loop to iterate through the elements of an array passed to a function, is there any better way?
Upvotes: 1
Views: 98
Reputation: 1974
1) This does not pass the entire array to the function. It passes a reference to the array. Since the compiler knows the type of the argument, it is able to do appropriate checks (when calling the function) and access array elements (within the function).
2) The declaration of the function (as opposed to the definition/implementation) would be;
void printArray(int (&a)[5]);
The name of the parameter (a
) is optional in this.
3) Since printing an object (including an array) does not typically change the object, it would be appropriate for the argument of printArray()
to be const
-qualified. This also allows the caller to pass a const
array (which is not possible in the code as shown). Furthermore, the type of i
used in the loop can also be a const
reference (which avoids copying elements of the array by value). It would also be possible to use automatic type inference (i.e. auto
). Increased const
-safety is often viewed as beneficial (since it increases chances of picking up attempts to modify something that should not be changed).
Upvotes: 2