We know that pointers store the address values of their operands.
As an example, if char *ptr=a
, ptr
will store the address of variable a
.
And any variable defined as a constant cannot change its value.
If const int a=5
, then any statement like a++
is invalid because this will alter the value of a which is prohibited.
Similarly if a pointer ptr
points to variable a
with declaration const int *ptr=a
. Statements like ptr=b
will be invalid because ptr
cannot point to b
as it is a constant pointer pointing to a
.
Having understood that, there happen to be two combinations of constants and pointers.
TYPE 1: Pointer to a constant
const int a=5;
int* const ptr=a;
In this case, the variable is a constant whose value cannot be modified.
Suppose the memory address of a is 0x9978
. Since, pointer stores address of variable, ptr=0x9978
.
Analyse the following statements:-
a=6; //Invalid: Value of a cannot be changed
*ptr=9; //Invalid: *ptr refers to a and will change its value.
int b=t;
ptr=b;//Valid: ptr is not constant and can point anywhere
Hope this concept is clear now.
TYPE 2: Constant pointer
Here the pointer is constant. Once it is pointed to a variable, it cannot point to any other variable. It stores a constant address throughout its life time.
int a=7;
const int* ptr=a;
Here the value of ptr(0x9978)
cannot be modified.
See the statements again:-
a=6; //Valid: Value of a can be changed
*ptr=9; //Valid: *ptr refers to a and its value can be altered.
int b=t;
ptr=b;//InValid: ptr is constant and cannot point anywhere else.
Thus, ptr
cannot point to any other variable now.
Coming to your question, to understand better, consider char *
not as a pointer but as a variable of string type(character buffer)!
char* barfoo = "variable_test"; //barfoo is a string storing 'variable_test'
const char* my_pointer_to_const_char = barfoo;
// This is type 2, constant pointer. Thus, my_pointer_to_const_char cannot
//point to any other variable and will always store the address of barfoo
barfoo = "changed!";
//this is perfectly valid as this statement will alter the value of string
//barfoo. my_pointer_to_const_char will still store the address of barfoo.
If there are still any doubts, feel free to comment:)