There are two topics related with constant and pointer is -
1. constant pointer
2. pointer to a constant
1. Constant Pointers
A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.
Sample Declaration: int * const ptr;
2. Pointer to a Constant
A pointer through which cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value at that address.
Sample Declaration: const int* ptr;
Sample Code
int main(void)
{
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2; // Invalid Operation as ptr is a constant pointer
}
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1; // Invalid operation as ptr is pointer to a constant
}
}
We have a concept of Constant Pointer to a Constant which is mix of two i.e. pointer can not point to another variable neither change the value of the variable it point to.
Sample Declaration: const int* const ptr;