See the below example:
int arr[10];
int *p = arr; // 1st valid choice
int (&r)[10] = arr; // 2nd valid choice
Now when we use auto
against arr
then, it chooses the 1st choice.
auto x = arr; // x is equivalent to *p
Is there a reason for choosing a pointer and not reference for array ?
The only reason for passing an array explicitly by reference is so that you can change the pointer to point to a different array. If a function only looks at the contents of an array, and does not change what is in the array, you usually indicates that by adding const to the parameter.
The auto&& keyword can be used as a universal reference value to bind to both an lvalue or an rvalue expression. Other uses of the auto keyword are iterators, class objects, function parameters, lambda functions, structured binding, references, and many more.
In simple words, array names are converted to pointers. That's the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same. There are a few cases where array names don't decay to pointers.
Pointer arithmetic is actually about 30% faster than using array indexes.
Yes. In that expression, the array decays into pointer type, due to lvalue-to-rvalue
conversion.
If you want array type , not pointer type, then do this:
auto & x = arr; //now it doesn't decay into pointer type!
&
in the target type prevents the array from decaying into pointer type!
x
is an array and not a pointer, can be proved as:
void f(int (&a)[10])
{
std::cout << "f() is called. that means, x is an array!" << std::endl;
}
int main() {
int arr[10];
auto & x = arr;
f(x); //okay iff x is an int array of size 10, else compilation error!
}
Output:
f() is called. that means, x is an array!
Demo at ideone : http://www.ideone.com/L2Ifp
Note that f
cannot be called with pointer type. It can be called with an int
array of size 10
. Attempting to call it with any other type, will result in compilation error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With