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)
?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With