I am learning about constant pointers and I was trying this
1 2 3 4 5 6 7 8 9 10
#include<iostream>
usingnamespace std ;
int main(){
int a = 10 ;
constint *cp = &a ; // my constant pointer variable
cout<<"\nAddress stored in cp = "<<cp ;
++cp;
cout<<"\nAddress stored in cp = "<<cp ;
}
It incremented the address which was stored in `cp`
But according to what I have understood until now, shouldn't `++cp` give an error as it is a constant pointer that always points to the same address and this address cannot be modified.
But when I replaced
[/code]const int *cp = &a ;[/code] with [/code]int *const cp = &a;[/code]
Then it gives me an error.
Forgive my ignorance but, aren't they suppose to mean the same thing ?
No constint * or intconst * means pointer to constant int: you can change pointer but not the value it points to int* const means const pointer: you cannot change pointer, but can change value it points to.
Yopu can freely mix those: constint* const or intconst * const means pointer you cannot change in any way.
By the way ++cp; in your program is illegal. Pointer arithmetics is only valid for pointers which points to the array, not the individual elements. Although it probably works as you expect, it is UB and in any more complex program this can lead to problems.