P. Danielski
P. Danielski

Reputation: 560

C++ Primer Exercise 2.25


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)

?

Upvotes: 5

Views: 557

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

You're very right to be confused.

I found the errata page, and it states

Page 59: Exercise 2.25 (a) should be int* ip, i, &r = i;

which makes a whole lot more sense.

(This should probably be a comment, but it's easier to read here...)

Upvotes: 7

David G
David G

Reputation: 96810

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;

Upvotes: 7

Related Questions