Your answers are very much sought to clear this major lacuna in my understanding about const
that I realized today.
In my program I have used the statement const int *ptr=&i;
but haven't used any const
qualifier for the variable i.Two things are confusing me:
1) When I try to modify the value of i using ptr
,where I have used const int *ptr=&i;
,I get the error assignment of read-only location '*ptr'|
,even though I haven't declared the variable i with the const
qualifier.So what exactly the statement const int *ptr=&i;
mean and how does it differ from int * const ptr=&i;
?
I had it drilled into my head that const int *ptr=&i;
means that the pointer stores the address of a constant,while int * const ptr=&i;
means the pointer is itself constant and can't change.But today one user told me in discussion(LINK) that const int *ptr means the memory pointed to must be treated as nonmodifiable _through this pointer_
.I find this something new as this kinda means "some select pointer can't alter the value(while others can)".I wasn't aware of such selective declarations!!But a 180k veteran attested to it that that user is correct!!.So can you state this in a clearer,more detailed and more rigorous way?What exactly does ``const int *ptr=&i; mean?
2) I was also told that we can lie to the program in the statement const int *ptr=&i;
by assigning the address of a non-constant to the pointer.What does it mean?Why are we allowed to do that?Why don't we get a warning if we assign the address of a non-constant to the pointer ptr
which expects address of a constant?And if it is so forgiving about being assigned address of non-constant,why it throws an error when we try to change the value of that non-constant,which is a reasonable thing to do,the pointed variable being a non-constant?
#include <stdio.h>
int main ()
{
int i=8;
const int *ptr=&i;
*ptr=9;
printf("%d",*ptr);
}
error: assignment of read-only location '*ptr'|