C ++ Exercise Exercise 2.25


there is an exercise (2.25) in the C ++ Primer 5th edition book that I cannot understand.

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

The book now provides an 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 doesn't the & r have the * operator in this exercise? Is there a difference in spelling

int *&r = ip;

      

or

int &r = ip;

      

(where ip is a pointer to int)

?

+3


source to share


2 answers


I think the author of this book thought that the signature int*

would do all comma-delimited declarations by making r

a pointer reference. Indeed, the code does not compile because it is wrong. ip

is declared as a pointer to int

, but is r

only declared as a reference to int

.

The compiler interprets

int * ip, &r = ip;

      

equivalent to

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

      



You need to add *

to declare as a reference to the pointer type:

int *op, *&r = ip;

      

You can also use typedef

:

typedef int* IntPtr;
IntPtr op, &r = ip;

      

+7


source


You are very right to be confused.

I found an error page and it says

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



which makes a lot more sense.

(This is probably a comment, but easier to read here ...)

+6


source







All Articles