Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a reference to an array work until we use a pointer?

Tags:

c++

reference

This works very well...

int a[5] = {1,2,3,4,5}, int *p = a;
int *& ref = p;

But why doesn't this work?

int a[5] = {1,2,3,4,5};
int*& ref = a;

Both a and p are pointers and have the same value (address of a[0]). When I make reference to an array using a pointer (p), it works very well.

But when I make reference to that array a[] directly, it doesn't work... Why?

like image 864
Gaurav Nag Avatar asked Jun 17 '17 06:06

Gaurav Nag


2 Answers

a is not a pointer, it is an array. It has the type int[5]. What it can do is decay to a pointer int*, which is what happens in the first case. So, taking a reference to p is ok.

Now for the second case. Remember that a is not a pointer. So, there is an implicit conversion happening from int[5] to int*. The result of that conversion is a prvalue. But you can't bind a non-const lvalue reference (which is what ref is) to an rvalue! So the code fails to compile.

Here's an analogy:

double a = 1.4;
int& b = a; // implicit conversion from 'double' to `int` results in prvalue
            // and you can't bind non-const lvalue refs to rvalues.
like image 97
Rakete1111 Avatar answered Oct 06 '22 06:10

Rakete1111


Adding on to what has already been answered, you can get a reference to an array like

int a[5];
int (&ref)[5] = a;

Live

like image 42
Passer By Avatar answered Oct 06 '22 06:10

Passer By