Reputation: 17
It is written in one book that we cannot change the memory refered by pointer to const like:-
int a = 0, b = 2;
const int* pA = &a; // pointer-to-const. `a` can't be changed through this
int* const pB = &a; // const pointer. `a` can be changed, but this pointer can't.
const int* const pC = &a; // const pointer-to-const.
//Error: Cannot assign to a const reference
*pA = b;
pA = &b;
*pB = b;
Then i written a code to check this and there i had declared pointer to const but changed its memory location and it got run but it should give error ->
#include <iostream>
int main()
{
int a=12;
const int* ptr;
ptr = &a;
std::cout<<*ptr<<"\n";
std::cout<<ptr<<"\n";
std::cout<<*ptr<<"\n";
int b=20;
ptr=&b;
std::cout<<*ptr;
return 0;
}
Upvotes: -1
Views: 275
Reputation: 171
If you are expecting your code should give error; change prt declaration to -
int* const ptr;
Refer this link it will help you understand in more details Clockwise/Spiral Rule
Upvotes: 0
Reputation: 238431
Read the comment from the code again:
const int* pA = &a; // pointer-to-const. `a` can't be changed through this
It doesn't say that the pointer cannot be changed. It is the pointed object that cannot be changed (through the pointer). a
is the object being pointed by pA
.
i had declared pointer to const but changed its memory location and it got run but it should give error
It shouldn't "give" error. You can change a 'pointer to const' i.e. you can make it point to another object. What you couldn't change is a const pointer. But your pointer isn't const.
Upvotes: 0
Reputation: 329
First let's understand what is the meaning of
const int *p;
The line above means that p is a pointer to a const integer. It means that p is holding the address of a variable which is of 'const int' type. This simply means that you can change the value of pointer 'p'. But the variable whose address 'p' is holding can't be changed because it is of const int type. Now, if you do
int* const p;
it means that the pointer now is of const type and is holding the address of an integer variable. So, here the pointer can't be changed but the value of the variable it is pointing to can be.
Upvotes: 1