Reputation: 227
Suppose we have
int *p1;
const int **pp2= &p1;
const int n=13;
// Which means we can't use pp2 to modify the value of the //variable whose address is stored in * pp2. * pp2 stores the address of some variable (n in this case below)
The book which I am reading -C++ primer says the following statement is perfectly legal
*pp2=&n;
I feel the above statement violates the matter written in comments above.
Could somebody please help clear this. Thanks a lot
Upvotes: 4
Views: 2902
Reputation: 322
It helps to understand it with a simple example. When you write the declaration below:
const int *p;
It says *p
is constant not p
. p
can store any address pointing to constant integer.
Similarly const int **p;
says pointer to pointer to a constant int. You can change p
and *p
but not **p
. *p
can hold any address pointing to constant integer like &n
in your case and you can change *P
with any addresses pointing to constant integer.
Upvotes: 3
Reputation: 1215
First, please pay attention that your example code, by itself, cannot compile (at least in the compiler I am using), as the line const int **pp2= &p1;
tries to assign an int **
to a const int **
- take a look here.
I believe that reading that page will help you understanding the problem you face either.
Upvotes: 2
Reputation: 170044
The type of &n
is int const *
.
The type of *pp2
is int const *
.
The const
qualifies the pointee, not the pointer, in this case.
So assigning one to the other is perfectly valid. The comment you quoted may be wrong, and should perhaps say:
// Which means we can't use **pp2 to modify the value of the
// variable whose address is stored in *pp2.
To elaborate :
int *p1;
The above creates a variable named p1
that can store the address of an int
. It's type is int*
. This statement doesn't initialize it, and so it hold an unspecified address (the value it can hold).
const int **pp2= &p1;
The above attempts to create and assign to a variable name pp2
. It's type is int const **
and the statement tries to assign it the address of p1
. Now the expression &p1
has the type int **
, and the assignment fails, since the const
qualifications mismatch.
As you can see, the code is in complete alignment with the (possibly corrected) statements.
Upvotes: 3