Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone help me understand this? int *& pr [duplicate]

I found this in a final exam:

int a = 564;
int* pa = &a;
int *& pr = pa;
cout << *pr;

According to the multiple choice answer, the code is valid, and displays the value of a.

But I'm confused about evaluation and precedence for line 3. Order of operations for C states that * and & have the same order. So, would it then be int *(&pr)? How can this be described in words?

Thank you.

like image 656
MercurialMadnessMan Avatar asked Jan 21 '23 22:01

MercurialMadnessMan


2 Answers

The third line defines a pointer reference (or a reference to a pointer, if you want). Assigning it to a pointer makes pr to actually be an alias to pa, and when evaluated, it points where pa points to, that is, a.

In the declaration of a variable, * and & don't have the meaning of operators, so precedence doesn't make sense here.

like image 145
Diego Sevilla Avatar answered Jan 30 '23 07:01

Diego Sevilla


It's a reference to a pointer. In C, you would express that as a pointer to a pointer.

You could write something like this:

// C++ style
void update_my_ptr(int*& ptr) { ptr = new int[1024]; }

// C style
void update_my_ptr_c(int **ptr) { *ptr = malloc(1024 * sizeof(int)); }

int main()
{
   int *ptr;
   update_my_ptr(ptr);
   // Here ptr is allocated!

}
like image 45
Maister Avatar answered Jan 30 '23 06:01

Maister