Consider the following program:
#include <iostream>
#include <cstring>
using namespace std;
void print(const char *pa) {
cout << "Print - using pointer" << endl;
}
void print(const char (&arr)[]) {
cout << "Print - using reference" << endl;
}
int main() {
char ca[] = {'B', 'A', 'D', 'C', '\0'};
print(ca);
}
Results:
Print - using reference
Why is reference preferred over pointers?
According to C Primer 5th Ed., section 6.6.1:
In order to determine the best match, the compiler ranks the conversions that could be used to convert each argument to the type of its corresponding parameter. Conversions are ranked as follows:
- An exact match. An exact match happens when:
• The argument and parameter types are identical.
• The argument is converted from an array or function type to the corresponding pointer type. (§ 6.7 (p. 247) covers function pointers.)
• A top-level const is added to or discarded from the argument.- Match through a const conversion (§ 4.11.2, p. 162).
- Match through a promotion (§ 4.11.1, p. 160).
- Match through an arithmetic (§ 4.11.1, p. 159) or pointer conversion (§ 4.11.2, p. 161).
- Match through a class-type conversion. (§ 14.9 (p. 579) covers these conversions.)
No mentioned of reference here. Any idea?
Thanks
CodePudding user response:
Binding a reference directly to an argument expression is considered as an identity conversion.
For the function with a parameter of a pointer type there is required the implicit conversion from an array type to the pointer type.
So the function with the referenced type of its parameter is more viable.
From the C 17 Standard (16.3.3.1.4 Reference binding)
1 When a parameter of reference type binds directly (11.6.3) to an argument expression, the implicit conversion sequence is the identity conversion, unless the argument expression has a type that is a derived class of the parameter type, in which case the implicit conversion sequence is a derived-to-base Conversion (16.3.3.1).