Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Primer Exercise 2.25

Tags:

c++


on C++ Primer 5th edition book there is an exercise (2.25) that I can't figure out.

Exercise 2.25: Determine the types and values of each of the following variables.
(a) int* ip, &r = ip;

Now, the book makes this example:

int i = 42;
int *p; // p is a pointer to int
int *&r = p; // r is a reference to the pointer p

So, my question is, why in that exercise the &r has not the * operator? Is there any difference writing

int *&r = ip;

or

int &r = ip;

(where ip is a pointer to int)

?

like image 625
P. Danielski Avatar asked Dec 12 '22 03:12

P. Danielski


1 Answers

I guess the author of that book thought that the signature int* would carry out to all of the comma-separate variable declarations, making r a reference to pointer. Indeed the code does not compile because this is not true. ip is declared as a pointer to an int and r is only declared as a reference to an int.

The compiler interprets

int * ip, &r = ip;

equivalently to

int * ip;
int & r = ip; // won't compile

You need an extra * to declare it as a reference to pointer type:

int *op, *&r = ip;

You can also use a typedef:

typedef int* IntPtr;
IntPtr op, &r = ip;
like image 164
David G Avatar answered Dec 29 '22 15:12

David G