if i had
int y, x;
const int *ptr=&y;
can i assign
ptr = &x;
if i had
int y, x;
const int *ptr=&y;
can i assign
ptr = &x;
Last edited by kuwait; 12-14-2002 at 04:07 PM.
please set free our POWs
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.
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
thanx for answering
another question
will x be constant in this case?
please set free our POWs
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).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
Last edited by Eibro; 12-14-2002 at 05:47 PM.
the pointer is const not x, x can be changed but not by that pointer.
none...
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...