• 12-14-2002
kuwait

int y, x;
const int *ptr=&y;

can i assign

ptr = &x;
• 12-14-2002
Magos
Yes. The pointer points to a (const int). It's not the pointer that is constant.
And you can have a const XXX pointer point at XXX (since something read and writable can be assumed only readable) but you cannot have a XXX pointer point at const XXX, since the pointer would allow you to write to something that is unwritable.
• 12-14-2002
kuwait

another question

will x be constant in this case?
• 12-14-2002
Eibro
Quote:

Originally posted by kuwait

another question

will x be constant in this case?

Sure, but it depends on which way you look at it. ptr promises not to change x, but if you had another pointer pointing to x (non-const) you could change it (or even just change x directly).

for example:

int x = 32;
const int *cptr = &x;
int *ptr = &x;

(*ptr)++; // Legal
(*cptr)++; // Illegal, cptr promises not to change the data it point to

Edit: Also worth mentioning that you can specify const pointers; using your first example, we can make it illegal to change what ptr points to, as well as make it illegal to change the data it points to.

int x,y;
const int * const ptr = &x;

ptr = &y; // Illegal, ptr is const
• 12-14-2002
ammar
the pointer is const not x, x can be changed but not by that pointer.
• 12-14-2002
Polymorphic OOP
if you want the pointer itself to be constant, then put const after the asterisk, IE

int* const ptr = &x;

ptr = &y; // ERROR: ptr is a constant

you can also do

const int* const ptr = &x;

which is a constant pointer to a constant int
• 12-14-2002
Eibro
Nominate this for the FAQ
Everyone give it a good score now...