Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When auto is used against array, why it's converted to pointer and not reference?

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 ?

like image 223
iammilind Avatar asked Jun 22 '11 16:06

iammilind


People also ask

Why are arrays automatically passed by reference?

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.

Can auto be a reference C++?

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.

Are arrays automatically pointers in C?

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.

Are pointer references more efficient than array indexes?

Pointer arithmetic is actually about 30% faster than using array indexes.


1 Answers

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.

like image 138
Nawaz Avatar answered Oct 22 '22 14:10

Nawaz