if i had
int y, x;
const int *ptr=&y;
can i assign
ptr = &x;
Printable View
if i had
int y, x;
const int *ptr=&y;
can i assign
ptr = &x;
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.
thanx for answering
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).Quote:
Originally posted by kuwait
thanx for answering
another question
will x be constant in this case?
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
the pointer is const not x, x can be changed but not by that pointer.
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
Nominate this for the FAQ
Everyone give it a good score now...