-1

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;
}
1
  • 1
    The first comment in your code explains why this works. You can't change the value pointed at by ptr, but you can change what ptr is pointing to. Commented Jul 2, 2020 at 12:24

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.