-2
int p=10;           
const int * ptr=&p;        // expression 1

As far as i understood by expression 1 that the data which is pointed by pointer ptr is constant

so if i write

*ptr=10;

which is invalid , but if i take another pointer variable like

int * pr=&p;
*pr=19;
cout<<*ptr;

will give me the ouput 19 so now the data pointed by ptr changed
but earlier we have seen that data pointed by ptr is constant
why data is changed by another pointer variable?

2 Answers2

2

const int * ptr=&p; means the data pointed to by ptr is const, but only relative to that pointer.

The pointed-to data is not necessarily really const (=originally declared const) and if it isn't, non-const pointers to it (including the original const-pointer cast to its non-const version) may change it.

If some data is really const, attempts to modify it through an non-const pointer result in undefined behavior.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
2

This is very basic, so my suggestion is to read a basic C++ book. Despite of that I'll provide the answer.

int p = 10;

It is a statement which declares and defines a variable named p of type int. The content of this variable can be modified. That's because the variable p is not const.

Obviously the later statement p = 13; is still valid and it assigns a new value to that variable.

Now you have this:

const int* ptr = &p;

You're defining a pointer, named ptr which points to that variable. Adding the qualifier const to the pointer it simply means that you cannot modify the content of the variable by means of the access of the pointer itself.

In other words, the pointer can be only used (for example) for reading the value of p.

On the other hand:

int* pr = &p;

defines a pointer which is not more const qualified.

Indeed, you can access and modify the content of the variable p by means of the usage of that pointer itself. (*pr = 19; is a valid statement).


A little bit far...

This is the general idea behind behind a "more complex world".

The statement:

const int* ptr = &p;

it's possible because the a variable can be implicitly converted in its const version.

BiagioF
  • 9,368
  • 2
  • 26
  • 50