pointer to pointer to const

why this code is illegal ?

1
2
3
4
int i = 10; 
int const *const cp = &i; 
int const **cp2 = &cp; 
//if i declare cp2 as a pointer to const i cannot modify nor cp nor i, why it is //illegal ?  


1
2
3
4
5
6
//but if i add another const qualifier 

	int i = 10; 
	int const *const cp = &i; 
	int const *const *cp2 = &cp; //why now it is legal ? 


can you help me with some advice for pointer to pointer to const ? i usally read them from the right to the left and put the const on the right



Last edited on
It isn't illegal.
Reading int const *const cp from right to left:

1
2
3
cp		cp is a...
*const		...const pointer to a...
int const	...const int.


Reading int const **cp2 from right to left:

1
2
3
4
cp2		cp2 is a...
*		...non-const pointer to a...
*		...non-const pointer to a...
int const	...const int.


Since cp is a const pointer &cp will give you a pointer to a const pointer, but cp2 is a pointer to a non-const pointer so obviously this is not allowed. If it was allowed it would be possible to modify cp through cp2 despite that cp is const.

1
2
3
4
5
6
7
8
int i = 10; 
int const *const cp = &i; 
int const **cp2 = &cp; // Imagine this was not an error.

// This would modify the const pointer cp, 
// which shouldn't be modified because 
// that's what const means.
*cp2 = 0;
Last edited on
int const *const cp = &i;
You cannot change the pointer cp, nor the value that it points to. Okay.

int const **cp2 = &cp;
cp2 is a pointer to a pointer to an int. You can change cp2, and you can change *cp2, but you can't change **cp2. In other words, you can't change the int, but you can change the point to it, and the pointer to the pointer.

However, you'd initializing it to point to cp, and cp ( the pointer to int) can change. This is why it's illegal.
Topic archived. No new replies allowed.